一、原题
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;
}
}