标签:
题目描述:(链接)
Given a linked list, swap every two adjacent nodes and return its head.
For example,
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.
Subscribe to see which companies asked this question
1 class Solution { 2 public: 3 ListNode *swapPairs(ListNode *head) { 4 if (!head || !(head->next)) { 5 return head; 6 } 7 8 ListNode dummy(-1); 9 dummy.next = head; 10 ListNode *prev = &dummy; 11 ListNode *cur = prev->next; 12 ListNode *next = cur->next; 13 14 while (next != nullptr) { 15 prev->next = next; 16 cur->next = next->next; 17 next->next = cur; 18 19 prev = cur; 20 cur = cur->next; 21 next = cur? cur->next : nullptr; 22 } 23 return dummy.next; 24 } 25 };
标签:
原文地址:http://www.cnblogs.com/skycore/p/4928334.html