【Leetcode】Swap Nodes in Pairs in JAVA 難得的一次寫對不帶改的。。附贈測試程式like always
阿新 • • 發佈:2019-01-25
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.
給一個連結串列,兩兩交換。我的思路是兩對兩對看,但是分為三種情況,這對和後面的情形是:1-2-3-4;1-2-3;1-2;
然後根據不同的情況寫出他們的交換策略~程式碼裡有註釋,看不懂的可以看註釋明白我的思路~
附贈main函式供各位測試!!!
public class SwapNodesinPairs { public static void main(String args[]){ SwapNodesinPairs dp = new SwapNodesinPairs(); ListNode head = new ListNode(1); ListNode p1 = new ListNode(2); head.next=p1; ListNode p2 = new ListNode(3); p1.next = p2; ListNode p3 = new ListNode(4); p2.next = p3; ListNode p4 = new ListNode(5); p3.next = p4; prinf(head); prinf(dp.swapPairs(head)); } private static void prinf(ListNode input){ while(input!=null) { System.out.print(input.val+"->"); input = input.next; } System.out.println(); } public ListNode swapPairs(ListNode head) { if(head==null||head.next==null) return head; ListNode p=head; ListNode start = head.next; while(p!=null&&p.next!=null){ ListNode nxt = p.next; //如果後面四個都有,2連向1,1連向4,4連向3,然後切記讓下一輪的p得等於3(但是由於這個演算法會跳過3,所以提前存好3) if(p.next.next!=null&&p.next.next.next!=null){ p.next=nxt.next.next; ListNode tmp = nxt.next;//提前存好3 nxt.next=p; p=tmp;//讓下一個p等於3,如果p.next的話下一個就是4了,而且3被永遠跳過了 } //如果後面有三個,就是這一對完了,還剩一個,那麼最後那個不動,這兩個交換 else if(p.next.next!=null&&p.next.next.next==null){ p.next=nxt.next; nxt.next=p; p=p.next; } //就剩最後兩個,自己交換即可 else if(p.next.next==null){ nxt.next=p; p.next=null; } } return start; } }