leetcode24:Swap Nodes in Pairs

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.

做题最重要的是思路清晰,思考全面,妈的!这一次又充分体会到了头结点的好处,拥有头结点可以简化操作

分三种情况:下一组节点不存;下一组节点只有一个节点;下一组节点存在,有两个节点。

public class leet24 {
	
	private class ListNode{
		int val;
		ListNode next;
		ListNode(){};
		ListNode(int x){ val = x;}
	}
		
	public static void main(String[] args) {
		
		leet24 leet = new leet24();
		
		ListNode head = new leet24().new ListNode();
		ListNode l1 = new leet24().new ListNode(1);
		ListNode l2 = new leet24().new ListNode(2);
		ListNode l3 = new leet24().new ListNode(3);
		ListNode l4 = new leet24().new ListNode(4);
		ListNode l5 = new leet24().new ListNode(5);
		ListNode l6 = new leet24().new ListNode(6);
		
		head.next = l1;
		l1.next = l2;
		l2.next = l3;
		l3.next = l4;
		l4.next = l5;
		l5.next = l6;
		
		ListNode result = leet.swapPairs(head);
		while(result.next != null){
			System.out.println(result.next.val);
			result = result.next;
		}		
	}
	public ListNode swapPairs(ListNode head){
		
		ListNode first = head.next;//组内第一个节点
		ListNode second = first.next;//组内第二个节点
		ListNode nextPairs = second.next;//下一组第一个节点
		head.next = second;//设置头结点
		while(first != null && second != null ){
			
			second.next = first;//第二个节点的后继指向第一个节点
			//当前第一个节点的的后继,的指向则要根据具体情况具体分析
			if(nextPairs == null){//如果下一组节点不存在,则节点,最后的节点指向空
				first.next = null;
				return head;//结束,返回
			}else if(nextPairs.next == null){//此时下一组节点存在,且只有一个节点
				first.next = nextPairs;//前一组的最后一个节点的后继,指向下一组的第一个节点
				return head;//结束			
			}else {//下一组节点存在,有两个节点
				first.next = nextPairs.next;//第二个节点的后继指向下一组的第二个节点
			}		
			first = nextPairs;//平移指针
			second = nextPairs.next;	
			nextPairs = second.next;
		}		
		return head;		
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值