LeetCode24.给定一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)
如果原始顺序是 dummyHead -> node1 -> node2,交换后面两个节点关系要变成 dummyHead -> node2 ->node1,事实上我们只要多执行一次next就可以拿到后面的元素,也就是类似node2 = temp.next.next这样的操作。
public class ReverseListTwoGroup {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
ListNode nodeA = initLinkedList(a);
ListNode d = null;
d=swapPairs(nodeA);
System.out.println(toString(d));
}
/**
* 两两反转
*/
public static ListNode swapPairs(ListNode head) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode cur = dummyHead;
while (cur.next != null && cur.next.next != null) {
ListNode node1 = cur.next;
ListNode node2 = cur.next.next;
cur.next = node2;
node1.next = node2.next;
node2.next = node1;
cur = node1;
}
return dummyHead.next;
}
/**
* 初始化链表
*/
private static ListNode initLinkedList(int[] array) {
ListNode head = null, cur = null;
for (int i = 0; i < array.length; i++) {
ListNode newNode = new ListNode(array[i]);
newNode.next = null;
if (i == 0) {
head = newNode;
cur = head;
} else {
cur.next = newNode;
cur = newNode;
}
}
return head;
}
/**
* 输出链表
*/
public static String toString(ListNode head) {
ListNode current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.val).append("\t");
current = current.next;
}
return sb.toString();
}
//定义链表节点
static class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}