Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4,you should return the list as 2->1->4->3.node
本题须要咱们对链表进行两两的交换,而且
1.如何交换表头
这里已经用过不少遍了,在链表的表头增长一个辅助节点。python
ListNode* result = new ListNode(-1); result->next = head;
2.如何进行链表的两两交换
链表的交换涉及到三个节点:当前节点(cur),当前节点的下一个节点(first),当前节点的下下个节点(second),交换原理如图1:.net
/** * 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 == nullptr || nullptr) return head; ListNode* result = new ListNode(0); result->next = head; ListNode* cur = result; while(cur->next != nullptr && cur->next->next != nullptr){ ListNode* first = cur->next; ListNode* second = cur->next->next; //节点交换 first->next = second->next; cur->next = second; cur->next->next = first; cur = cur->next->next; } return result->next; } };
/** * 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 == nullptr || head->next == nullptr) return head; ListNode* result = head -> next; head->next = swapPairs(result->next); result->next = head; return result; } };