【剑指Offer】反转链表

题目

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

实现

1
2
3
4
5
6
7
8
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ListNode ReverseList(ListNode head) {
ListNode current = head;
ListNode previous = null;
ListNode tail = null;

while (current != null){
ListNode next = current.next;

if (next == null)
tail = current;

current.next = previous;
previous = current;
current = next;
}

return tail;
}