欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

24. Swap Nodes in Pairs 链表每2个点翻转一次

发布时间:2025/3/15 编程问答 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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个点翻转一次的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。