给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定1->2->3->4
, 你应该返回2->1->4->3
.
/**
* 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) {
if (head == NULL || head->next == NULL) return head;
//取出next节点
ListNode* nextnode = head->next;
head->next = swapPairs(nextnode->next);
//将next结点的next值设为head, 此时实现了head结点以及其next的法装
nextnode->next = head;
//反转后 原next结点作为新的节点
return nextnode;
}
};
python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
tmp =head.next # 取出next 结点
r = self.swapPairs(tmp.next) # 将head 头结点的next设为next的next结点
tmp.next = head # 将next 结点的next设置为head 此时实现了head节点 机器next节点的反转
head.next = r # 反转后将原next节点作为新的next节点
return tmp