24. Swap Nodes in Pairs 链表每2个点翻转一次
[抄题]:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
[暴力解法]:
时间分析:
空间分析:dummy node,新建才是n,不新建就是1
[优化后]:
时间分析:
空间分析:recursive用的是stack, 空间恒定为n.
特例:尾递归是1
[奇葩输出条件]:
[奇葩corner case]:
从节点非空就行了
[思维问题]:
不知道指针用什么顺序交换:
先外后里,外面的两点前后无所谓。
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
用一个cur做主节点 负责移动,一个first second分别做后面两个从节点(因此循环条件就是从节点非空?)
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
学了很多:先外后里,左指右,从节点非空
[复杂度]:Time complexity: O(n) Space complexity: O(1)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ class Solution {public ListNode swapPairs(ListNode head) {//ccif (head == null) return head; //ini: dummy nodeListNode dummy = new ListNode(0);dummy.next = head;ListNode cur = dummy;//while loop if the two nodes are not nullwhile (cur.next != null && cur.next.next != null) {//initialize two ListNodeListNode first = cur.next;ListNode second = cur.next.next;//change the pointercur.next = second;first.next = second.next;second.next = first;//move the curcur = cur.next.next;}return dummy.next;} } View Code
转载于:https://www.cnblogs.com/immiao0319/p/9397580.html
总结
以上是生活随笔为你收集整理的24. Swap Nodes in Pairs 链表每2个点翻转一次的全部内容,希望文章能够帮你解决所遇到的问题。