您的位置:首页 > 编程语言 > C语言/C++

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
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: