leetcode24题 题解 翻译 C语言版 Python版
2016-04-14 20:46
531 查看
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
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,那么此方法不适用,可以单独处理。另外由于第一个结点没有前置结点,所以第一和第二结点的交换需要单独处理。
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
相关文章推荐
- C++标准库和标准模板库
- c++的三次作业
- MFC的多国语言界面的实现
- C++关于模板
- C语言(二叉树)
- C++中智能指针的设计和使用
- c++ RAII
- C++中 vector、list、deque、set、map的底层实现
- c++ 通用类型
- C++ string 字符串函数详解
- C语言中的static 详细分析
- c语言:抽签游戏实现
- 深入理解C++的动态绑定和静态绑定
- 排列生成器详解+实例 (C++实现)
- C++匿名命名空间
- C++ 入门
- Kmeans聚类c++实现
- 求两个已排序单链表中相同的数据(C语言)
- 求链表相交时的交点(C语言)
- 判断两个链表是否相交,若相交,求交点。(假设链表可能带环)【升级版】(C语言)