LeetCode24 Swap Nodes in Pairs 成對交換鏈結表節點,leetcode24交換鏈結
題目:
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.
翻譯:
給你一個鏈表,交換每兩個相連的節點。
思路:
就是節點交換問題。只要儲存頭結點,且要理清交換的節點的位置問題。
代碼:
public ListNode swapPairs(ListNode head) { ListNode root = new ListNode(0);//建立個首節點指向鏈表開始 root.next = head; ListNode pre = root;//前一個節點 while(head!=null && head.next!=null) { ListNode t = head.next.next; pre.next = head.next; pre.next.next = head; head.next = t; pre = head; head = t; } return root.next; }
首先得保證該節點和下一個節點存在。
接著就是交換問題。 假設 現在的鏈表是1->2->3->4 。首先建立個root節點,他的next指向頭部。
第一次迴圈:pre指向root,head指向1,要交換12,首先的儲存2的下一個節點3,用t表示,接著使得pre的next為2 ,即head的next;接著2的下一個節點為1,於是乎pre.next.next = head.最後head的下一個為3,即head.next = t。
此時鏈表為2-1-3-4.此時使得指標跳2個。即pre指向1,head指向3即可。然後繼續迴圈實現交換。