/**
 * ID: 24
 * Name: Swap Nodes in Pairs
 * Data Structure: Linked List
 * Time Complexity:  
 * Space Complexity:  
 * Tag: LinkList
 * Difficult: Medium
 
 * Problem: 
 * Given a linked list, swap every two adjacent nodes and return its head.
 * Given 1->2->3->4, you should return the list as 2->1->4->3. 
 * Your algorithm should use only constant space. 
 * You may not modify the values in the list, only nodes itself can be changed.
思路一:
使用 pre, start , then方法,来处理反转,插入的操作,然后注意整个数组的长度是偶数还是奇数。
1 class Solution { 2 public: 3 ListNode *swapPairs(ListNode *head) { 4 if(head==NULL || head->next == NULL) 5 return head; 6 ListNode * fakeNode = new ListNode(0); 7 fakeNode -> next = head; 8 ListNode * pre = fakeNode; 9 ListNode * start = pre->next; 10 ListNode * then = start -> next; 11 while(then) 12 { 13 start -> next = then -> next; 14 then -> next = pre ->next; 15 pre->next = then; 16 then = start -> next; 17 pre = start; 18 if(pre->next==NULL) 19 break; 20 start = start ->next; 21 then = start->next; 22 } 23 return fakeNode->next; 24 } 25 };
思路二:
1 // recursive will be a little slower. 2 class Solution { 3 public: 4 ListNode *swapPairs(ListNode *head) { 5 if(head==NULL || head->next == NULL) 6 return head; 7 ListNode *next = head->next; 8 ListNode *nextnext = next->next; 9 head ->next = this->swapPairs(nextnext); 10 next ->next = head; 11 return next; 12 } 13 };
                    
                
                
            
        
浙公网安备 33010602011771号