Leetcode016--链表相邻元素进行交换

一、原题



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,3,5,7 和交换之后就是3,1,7,5


四、思路



首先建立一个新的链表的头结点指向已有链表的结点,再建立一个指向链表尾结点的指针P,指向链表的尾结点,然后进行交换。



五、程序



package LeetCode;

class ListNodeSwap {
    int val;
    ListNodeSwap next;

    ListNodeSwap() {}
    
    ListNodeSwap(int x) {
        val = x;
        next = null;
    }
}

public class Leetcode017 {
	
	public static void main(String args[]){
		ListNodeSwap n1 = new ListNodeSwap(1);  
		ListNodeSwap n2 = new ListNodeSwap(2);  
		ListNodeSwap n3 = new ListNodeSwap(3);  
		ListNodeSwap n4 = new ListNodeSwap(4);  

        n1.next = n2;  
        n2.next = n3;  
        n3.next = n4;  
  
        
        ListNodeSwap list = new ListNodeSwap();
        list = MergeTwoList(n1);
        
        while(list != null){
        	System.out.print(list.val+" ");
        	list = list.next;
        }
	}

	
    /**
     * 将链表的相邻元素进行两两交换
     */
    public static ListNodeSwap MergeTwoList(ListNodeSwap head) {
    	
    	if(head == null){
    		return null;
    	}

    	//建立一个新的链表用于存储
    	ListNodeSwap root = new ListNodeSwap();
    	root.next = head;
    	
    	//p指向链表的尾结点
    	ListNodeSwap p = root;
    	ListNodeSwap tmp;
    	
    	while(p.next != null &&p.next.next != null){		
    		//下一次要处理的位置
    		tmp = p.next.next;
    		
    		//通过三个步骤进行交换
    		p.next.next = tmp.next;
    		tmp.next = p.next;
    		p.next = tmp;
    		
    		p = tmp.next;
    	}

    	head = root.next;
    	root.next = null;
    	
    	return head;
    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值