这篇是翻转链表的一些题。
题目 | 简介 |
---|---|
206. Reverse Linked List | 普通翻转 |
24. Swap Nodes in Pairs | 两个一组,普通翻转 |
92. Reverse Linked List II | 依次从后端拿出元素插入前端,m到n |
25. Reverse Nodes in k-Group | 依次从后端拿出元素插入前端,每k个 |
206. Reverse Linked List
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
方法一:iterative
geekforgeek上有个很棒的动画:翻转链表小动画
注意:
1.head==null不用单独讨论。
2.不用加dummy,pre可以先赋值为null。
// iterative
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
//move pointers
pre = cur;
cur = temp;
}
return pre;
}
}
方法二:recursive
写这种链表recursive的,方法是focus on某一步。比如,假装我们就只处理“下级已经帮我翻转好2到5了,传给我了如上图第二行的链表,我需要把它修改成为1到5都翻转好的,如上图第三行的链表”。
处理当前这一步的时候,先把head.next这个节点(远的)的next指向处理妥当,再处理head(近的)的next指向。
// recursive
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null