LeetCode Swap Nodes in Pairs

来源:互联网 发布:淘宝店铺粉丝最多 编辑:程序博客网 时间:2024/06/06 08:52

题意:给出一个单链表,每两个一组相互交换,不能通过交换每组的值来实现

思路:

1、链表为空或者只有一个结点,不需要交换

2、有两个结点时p,q,其中q = p.next,交换用p.next = q.next,q.next = p

3、在有多于2个结点时,以4个为例,前一组交换后的结点的后继结点应该是后一组结点未交换前的第二个

具体代码如下:

class ListNode{    int val;    ListNode next;    ListNode(int x) { val = x;}}class Solution{    public ListNode swapPairs(ListNode head)    {        if (null == head || null == head.next) return head;        ListNode cur = head, next = cur.next;        ListNode newHead = next;        cur.next = next.next;        next.next = cur;        if (null == cur.next) return newHead;        while (cur.next.next != null)        {            ListNode pre = cur;            cur = cur.next;            next = cur.next;            pre.next = next;            cur.next = next.next;            next.next = cur;            if (null == cur.next) break;        }        return newHead;    }}


0 0
原创粉丝点击