Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

24. Swap Nodes in Pairs #5

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

新建一个头0,两个指针代表pair的两个元素,1st挂第三个,头0挂2nd,把1st挂在2nd后,移动位置。 public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; ListNode subs = new ListNode(0); subs.next = head; ListNode flag = subs; //subs.next = head; while(flag.next != null && flag.next.next != null) { ListNode p1 = flag.next; ListNode p2 = flag.next.next; p1.next = p2.next; flag.next = p2; flag.next.next = p1; flag = flag.next.next; } return subs.next; } }