leetcode 題解 || Swap Nodes in Pairs 問題
阿新 • • 發佈:2019-02-01
problem:
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.
在單鏈表中,每兩個結點交換一下位置,單個的不交換
thinking:
(1)這道題在不新建結點的情況下,指向關係複雜,慢慢分析
(2)head是頭指標,指向第一個有效結點!!!
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { ListNode *index = head; ListNode *pre = NULL; ListNode *tmp = NULL; ListNode *modify = head;; int i=0; if(head==NULL||head->next==NULL) return head; while((index!=NULL)&&(index->next!=NULL)) { i++; pre=index; if(i==1) { head=pre->next; index = index->next; tmp = index->next; pre->next = tmp; index->next = pre; index=tmp; modify=pre; } else { index = index->next; tmp = index->next; modify->next=pre->next; pre->next = tmp; index->next = pre; index=tmp; modify=pre; } } return head; } };