LeetCode24之SwapNodesInPairs的Java 题解

题目:

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,记录下一次需要遍历的节点(在后面操作中会改变指向,如不记录链表会断裂)next=curr.next;

2,使第二个节点指向第一个节点。curr.next=pre.next;

3,使表头指向第二个节点。pre.next=curr;这时候pre->节点2->节点1

4,移动pre指针到节点1。pre=cur;

5,使pre的next指向下一次需要进行处理的第一个节点。pre.next=next;

6,cur指针移动到下一次需要进行处理的第一个节点。cur=next;

代码:

public static ListNode swapPairs(ListNode head) {
		if(head==null||head.next==null)
			return head;
		ListNode fakeNode=new ListNode(-1);
		fakeNode.next=head;
		ListNode pre=fakeNode,cur=head,next=null,curr=null;
		while(cur!=null&&cur.next!=null)
		{
			curr=cur.next;//用一个变量记录,在后面调用中减少多次节点二重指向,能够减少运行时间
			next=curr.next;
			curr.next=pre.next;
			pre.next=curr;
			pre=cur;
			pre.next=next;
			cur=next;
		}
		return fakeNode.next;
			
        
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值