题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路
代码
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head:
return None
root = ListNode(-1)
root.next = head
pre = root
while(pre.next != None and pre.next.next != None):
start = pre.next
end = pre.next.next
pre.next = end
start.next = end.next
end.next = start
pre = start
return root.next
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *pre = new ListNode(0);
pre->next = head;
ListNode *temp = pre;
while(temp->next != nullptr && temp->next->next != nullptr) {
ListNode *start = temp->next;
ListNode *end = temp->next->next;
temp->next = end;
start->next = end->next;
end->next = start;
temp = start;
}
return pre->next;
}
};