CS100-Linked Lists.pptx

advertisement
Linked Lists
As you arrive…please snarf today’s
classwork
The Code Handout
1. What is the output of this code? Write A-F on
the sheet.
2. Once you have answered the questions, run the
code itself in Eclipse and verify your answer. If
you got any wrong, figure out where you went
wrong.
3. The nodes (beginning with NodeX) make a list.
Modify the code to add a node with data “4” to
the beginning of the list and a node with data
“5” to the end of the list
public class ListNode {
public int data;
public ListNode next;
}
Each ListNode object has a next pointer that either points to null or to the next
element in the list.
head
Data: 5
Next:
Data: 77
Next:
Data: 2
Next: null
The Code Reprise
1. If you haven’t yet: the nodes (beginning with
NodeX) make a list. Modify the code to add a
node with data “4” to the beginning of the
list and a node with data “5” to the end of
the list
2. Try to write the function generateList.
generateList should generate a list of n
nodes, each with value. It should return a
pointer to the node at the head of the list.
Mysterious Code
• The function addZeroAsSecondElement works,
but the function addZeroAsFirstElement is
broken. Figure out why if you can and fix it.
• OR (if you get stuck or finish)…write
addZeroAsThirdElement. Be sure your code
works with lists of length 0-3 elements.
• When you are finished, submit your code via
Ambient
Download