Swap Nodes in Pairs

来源:互联网 发布:appserv怎么进入mysql 编辑:程序博客网 时间:2024/05/29 10:01

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交换。

用到的操作和链表逆置那道题差不多,这种题目只要画画图,把指针依次怎么指向的过程搞清楚就行了。这道题因为头结点

会发生改变,所以使用一个dummy节点会比较方便操作。

其中:dummy.next = head,pre = dummy,cur1 = pre.next,cur2 = cur1.next。现在画图来演示交换过程。 


class Solution {    public ListNode swapPairs(ListNode head) {        if(head == null) {        return null;        }        ListNode dummy = new ListNode(0);        dummy.next = head;        ListNode pre = dummy;        ListNode cur1 = pre.next;        ListNode cur2 = cur1.next;        while(cur2 != null && cur1 != null) {        ListNode tmp = cur2.next;        pre.next = cur2;        cur2.next = cur1;        cur1.next = tmp;            pre = cur1;            cur1 = cur1.next;            if(cur1 != null) {            cur2 = cur1.next;            }        }        return dummy.next;    } }


原创粉丝点击