Swap Nodes in Pairs

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.

题目理解:不要交换链表节点的值,而是直接交换链表相邻的(奇数+偶数)节点对。时间复杂度控制在O(n),空间复杂度控制在O(1)。

题目思路:记录当前节点的父和祖先节点位置,每遍历到一组节点对,就触发一次交换。

import java.lang.Math;

class ListNode {
	int val;
	ListNode next;
	ListNode(int x) { val = x; }
}

public class Solution {
    public ListNode swapPairs(ListNode head) {
        boolean ifrecord=true;	
        ListNode pparent=new ListNode(0);
        //LeetCode里的链表从第一个节点就是开始保存数据了,所以要新建一个节点来抓住输入链表的头。
        pparent.next=head;
        
        ListNode parent=null,Pchild=head;
        head=pparent;	//把head重定义了,haed不是head了
        while(Pchild!=null){	//只要还没扫到链表末尾
        	if(ifrecord==true){
        		//布尔类型来标记当前是否进到了新的一组,要交换的俩节点里,ifrecord==true,将当前节点记为父节点。
        		parent=Pchild;	
        	}else{
        		/**
        		 * 用1,2举例,设pparent->0,1,2,3,4; parent->1,2,3,4;Pchild->2,3,4;
        		 */
        		Pchild=parent;			//Pchild->1,2,3,4;parent->1,2,3,4;pparent->0,1,2,3,4;
        		parent=parent.next;		//Pchild->1,2,3,4;parent->2,3,4;pparent->0,1,2,3,4;
        		Pchild.next=parent.next;//Pchild->1,3,4;parent->2,3,4;pparent->0,1,2,3,4;
        		parent.next=Pchild;		//Pchild->1,3,4;parent->2,1,3,4;pparent->0,1,2,3,4;
        		
        		pparent.next=parent;	//Pchild->1,3,4;parent->2,1,3,4;pparent->0,2,1,3,4;
        		pparent=Pchild;			//Pchild->1,3,4;parent->2,1,3,4;pparent->1,3,4;
        								//至此12交换完毕,下一轮交换34
        	}
        	Pchild=Pchild.next;
        	ifrecord=(!ifrecord);
        }
        return head.next;
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值