LeetCode-24.Swap Nodes in Pairs

时间:2019-03-19
本文章向大家介绍LeetCode-24.Swap Nodes in Pairs,主要包括LeetCode-24.Swap Nodes in Pairs使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

 Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
 1 public ListNode swapPairs(ListNode head) {//链表my
 2         ListNode nhead = new ListNode(0);
 3         nhead.next=head;
 4         ListNode cur=head;
 5         ListNode pre = nhead;
 6         while(null!= cur&&null!=cur.next){
 7             pre.next = cur.next;
 8             cur.next=pre.next.next;
 9             pre.next.next=cur;
10             pre=cur;
11             cur=cur.next;
12         }
13         return nhead.next;
14     }

方法一样,但可读性更高的代码

public ListNode swapPairs1(ListNode head) {
        ListNode nhead = new ListNode(0);
        nhead.next=head;
        ListNode pre = nhead;
        while(null!= pre.next&&null!=pre.next.next){
            ListNode fitst= pre.next;
            ListNode second = pre.next.next;
            pre.next=second;
            fitst.next=second.next;
            second.next=fitst;
            pre=fitst;
        }
        return nhead.next;
    }