面试题16:反转链表

题目:题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

解答:

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
32
33
34
35
36
37
38
package offer;
public class {
static class ListNode{
int data;
ListNode next;
}
public ListNode ReverseList(ListNode head){
if(head == null)
return null;
ListNode preListNode = null;
ListNode nowListNode = head;
while(nowListNode != null){
ListNode nextListNode = nowListNode.next;
nowListNode.next = preListNode; //当前结点指向前一个结点
preListNode = nowListNode; //前任结点 到现任节点
nowListNode = nextListNode; //现任节点到下一结点
}
return preListNode;
}
public static void main(String[] args){
ListNode head = new ListNode();
ListNode second = new ListNode();
ListNode third = new ListNode();
ListNode forth = new ListNode();
head.next = second;
second.next = third;
third.next = forth;
head.data = 1;
second.data = 2;
third.data = 3;
forth.data = 4;
t16 test = new t16();
ListNode result = test.ReverseList(head);
System.out.println(result.data);
}
}