题目描述:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
解题思路:
每次做完一对之后,让p指向当前a的位置
C++写法:
代码:
/**
* 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) {
auto dummy = new ListNode(-1);
dummy -> next = head;
for(auto p = dummy; p -> next && p -> next -> next;)
{
auto a = p -> next, b = a -> next;
p -> next = b;
a -> next = b -> next;
b -> next = a;
p = a;
}
return dummy -> next;
}
};
python写法:
# 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):
dummy = ListNode(-1)
dummy.next = head
p = dummy
while p.next and p.next.next:
a = p.next
b = a.next
p.next = b
a.next = b.next
b.next = a
p = a
return dummy.next
题目来源: