翻转链表

链表的结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ListNode {
int val;
ListNode next;

ListNode() {}

ListNode(int val) {
this.val = val;
}

ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}

翻转链表的算法:

1
2
3
4
5
6
7
8
9
10
11
12
13
public ListNode reverseNode(ListNode l) {
if (l == null || l.next == null)
return l;
ListNode p = l, pre = null, next = null;
while (p.next != null) {
next = p.next;
p.next = pre;
pre = p;
p = next;
}
p.next = pre;
return p;
}
坚持原创技术分享,感谢您的支持和鼓励!