Swap Nodes in Pairs
Description
Given a linked list, swap every two adjacent nodes and return its head.
Example Given 1->2->3->4, you should return the list as 2->1->4->3.Challenge
Your algorithm should use only constant space.
You may not modify the values in the list,
only nodes itself can be changed.
Link
Method
- x
- x
Example
- 1
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * @param head a ListNode * @return a ListNode */ ListNode* swapPairs(ListNode* head) { // Write your code here if (!head) { return nullptr; } if (!head->next) { return head; } ListNode dummy(0); dummy.next = head; ListNode* prev = &dummy; ListNode* cur = dummy.next; //(dummy)prev-> cur-> curnext -> curnextnext while (cur && cur->next) { ListNode* rest = cur->next->next; ListNode* one = prev->next; ListNode* two = cur->next; // prev --> two // two --> one prev->next = two; two->next = one; // cur one->next = rest; // advance prev = one; cur = one->next; } return dummy.next; } };
Similar problems
x
Tags
x