标签:white ini null logs eve pre 使用 栈结构 ant
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *swapPairs(ListNode *head) { 12 if(head == NULL) 13 return NULL; 14 int k = 2; 15 stack<ListNode *> s; 16 ListNode *p = head; 17 ListNode *newHead = new ListNode(0); 18 ListNode *newP = newHead; 19 int tmp = 0; 20 while(p != NULL) 21 { 22 if(tmp<k) 23 { 24 s.push(p); 25 p = p->next; 26 tmp++; 27 } 28 if(tmp == k) 29 { 30 while(!s.empty()) 31 { 32 newP->next = s.top(); 33 s.pop(); 34 newP = newP->next; 35 tmp--; 36 } 37 } 38 39 } 40 stack<ListNode *>s2; 41 while(!s.empty()) 42 { 43 s2.push(s.top()); 44 s.pop(); 45 } 46 while(!s2.empty()) 47 { 48 newP->next = s2.top(); 49 s2.pop(); 50 newP = newP->next; 51 } 52 newP->next = NULL; 53 return newHead->next; 54 } 55 };
leetcode链表--16、swap-nodes-in-pairs(成对交换链表结点)
标签:white ini null logs eve pre 使用 栈结构 ant
原文地址:http://www.cnblogs.com/qqky/p/6917297.html