leetcode反转链表


输入一个链表,反转后输出所有元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ListNode{
int val;
ListNode next;
ListNode(int x) {val = x; }
}

public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode next = null;
ListNode pre = null;

while(head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}

}