Now that you know how to build a list from front to back, let’s build one in the
ID: 3779423 • Letter: N
Question
Now that you know how to build a list from front to back, let’s build one in the opposite direction: backtofront. In other words, the last node will be added first and the first node will be added last. We’ll let you do this one by yourself, but some hints:
1) Start the same way – create one node outside and before the loop, assign a head pointer to point to it, and assign its next pointer to NULL
2) While the fronttoback program we wrote above keeps the head pointer constant and adds new nodes to the next pointer of the last node, the backtofront list builder will have to continually reset the head pointer to the newest node added.
3) So, you will write a for loop and inside it, write statements that, in each iteration, move the head pointer to the new node being added after the new node’s next pointer is redirected to the head pointer. The after is important because if it is done before, the list will be lost forever.
Explanation / Answer
public class ListNode { private int data; private ListNode next; public ListNode(int data) { this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public ListNode getNext() { return next; } public void setNext(ListNode next) { this.next = next; } ListNode reverseList(ListNode head) { ListNode temp= null,nextNode = null; while(head!=null) { nextNode = head.getNext(); head.setNext(temp); temp = head; head = nextNode; } return temp; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.