leetcode24题 题解 翻译 C语言版 Python版

24. 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.

24.成对交换结点

给定一个链表,交换相邻的两个结点并返回链表头

举个例子:

给定1->2->3->4,你应该返回2->1->4->3。

你的算法只能使用恒定空间。你不能去修改链表结点中保存的值,而只能去改变结点的指向。


思路:交换两个结点肯定至少要保留两个游动指针,如果两个指针分别指向当前要交换的两个结点的话就无法回溯到上一个结点了,这样链表就断裂了。所以两个游走指针应当分别指向上一个结点和当前要交换的两个结点的第一个,然后通过改变指向的操作打断三次连接三次,达到调转的目的。那么循环的结束可以有两种情况,一种是当前交换后后面没有结点了,另一种是后面只有一个结点。需要注意如果开始整个链表的结点数就小于2,那么此方法不适用,可以单独处理。另外由于第一个结点没有前置结点,所以第一和第二结点的交换需要单独处理。


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    if (!head) return NULL;
    if (!head->next) return head;
    
    struct ListNode* t = head->next->next;
    head->next->next = head;
    head = head->next;
    head->next->next = t;
    if (!t) return head;
        
    struct ListNode *p1, *p2;
    p1 = head->next;
    p2 = p1->next;
    while (p2->next){
        p1->next = p2->next;
        p2->next = p2->next->next;
        p1->next->next = p2;
        if (!p2->next) break;
        p1 = p2;
        p2 = p2->next;
    }
    return head;
}


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head: return None
        if not head.next: return head
        
        t = head.next.next
        head.next.next = head
        head = head.next
        head.next.next = t
        if not t: return head
        
        p1 = head.next
        p2 = p1.next
        while p2.next:
            p1.next = p2.next
            p2.next = p2.next.next
            p1.next.next = p2
            if not p2.next: break
            p1 = p2
            p2 = p2.next
        return head




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值