leetcode之 Swap Nodes in Pairs
阿新 • • 發佈:2018-12-14
題目:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
程式碼:
#include<iostream> #include<vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* swapPairs(ListNode* head) { if (!head) return NULL; ListNode* p = head; if (!p->next)return head; ListNode* q = p->next; ListNode* last = head; int i = 0; while (p&&q) { p->next = q->next; q->next = p; if (i == 0)head = q; else last->next = q; last = p; p = p->next; if (p) { q = p->next; } i++; } return head; } int main() { ListNode* l1 = new ListNode(1); ListNode* l2 = new ListNode(2); ListNode* l3 = new ListNode(3); ListNode* l4 = new ListNode(4); ListNode* l5 = new ListNode(5); ListNode* l6 = new ListNode(6); l1->next = l2; l2->next = l3; l3->next = l4; l4->next = l5; l5->next = l6; ListNode* l = swapPairs(l1); while (l) { cout << l->val << " "; l = l->next; } return 0; }