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; } };