题目:将链表的奇数位和偶数位调换组成新的链表

    xiaoxiao2026-01-08  11

    题目:将链表的奇数位和偶数位调换组成新的链表

    原题链接: http://oj.leetcode.com/problems/swap-nodes-in-pairs/

    Given a linked list, swap every two adjacent nodes and return its head.For example,

    Given 1->2->3->4, you should return the list as 2->1->4->3.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed

    # 分析

    struct ListNode* swapPairs(struct ListNode* head)

    Q1

    Given 1->2->3->4, you should return the list as 2->1->4->3head指向第一个元素 1 函数指针传递是传递 无论如何交换参数head不可能返回指向元素2 如何解决?

    必须重新建立一个新的链表 进行返回

    采用 带头节点单链表

    知识补充:带头节点单链表和不带头节点单链表有什么区别

    ****<u>

    带头结点单链表好处解决了 不用判断第一个节点是否为空 不需要特殊处理

    用统一方法实现就 例如 链表insert操作**返回值是最新链表 struct ListNode head 不是*

    Q2: 链表遍历操作 ptr(A)=ptr->next(B) 前提条件节点A和节点B 位置关系没有发现变化

    在链表排序(交换位置是排序一个方法)原来位置发生改变如何处理 ? 需要临时遍历记录 下 B位置链表交换节点 影响不是2个 而是三个 不要忘记最后 1 -2-3 A=2 B=32-1-3 A=2 B=1 >>A=1 B=3

    解题思路如下

    第一次循环处理结果:root: 0 ->1->2->3 ->4 之前 pre=0 cur=1

    root: 0 ->2->1->3->4 之后 pre=1 cur=3pre相对于原来排序移动2次

    code

    /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode* next; * ListNode(int x): val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { //head节点 ListNode root(0); root.next =head; ListNode * pre=&root;//0 ListNode * cur =head;//1 while(cur && cur->next) { //swap pre->next=cur->next;// 0 --> 2 cur->next=pre->next->next;//1 --> 3 pre->next->next=cur;//2->1 pre=cur;// 虽然 pre 仍然指向 位置1 原来位置1 swap之后放到位置2后面 cur=cur->next;//pre ->1 cur->3 节 //0 ->2->1->3->4 } return root.next; } };

    执行行效率分析:https://leetcode.com/submissions/detail/102239317/

    耗时6ms不是最优解呀

    耗时应该在建立头节点 如果不用头节点 需要特殊处理 第一次处理时候null查看耗时3秒的 提取到函数外面 为了防止异常数据 异常判断

    为了完成遍历 采用三个节点 first second three 三个节点

    关注微信公共账号

    最新回复(0)