aboutsummaryrefslogtreecommitdiff
path: root/ReverseList.java
blob: 96e09a2f4c79afa6766c4fd493c0d87342b82188 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.lang.*;
import java.util.*;
import node.*;

class ReverseList {
	public static ListNode reverseList(ListNode head) {
		ListNode prev = null;
		ListNode node = head;
		while (node != null) {
			ListNode tmp = node.next;
			node.next = prev;
			prev = node;
			node = tmp;
		}
		return prev;
	}

	public static void main(String[] args) {
		ListNode fourth = new ListNode(5, null);
		ListNode third = new ListNode(4, fourth);
		ListNode second = new ListNode(3, third);
		ListNode first = new ListNode(2, second);
		ListNode head = new ListNode(1, first);

		ListNode curr = reverseList(head);
		while (curr != null) {
			System.out.println(curr.val);
			curr = curr.next;
		}
	}
}