package com.zmz.algorithm.listnode;
/**
* @author 张明泽
* Create by 2022/5/28 17:28
* 两两交换链表中的节点
* LeetCode-24
*/
public class SwapPairNode {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
head.next = node2;
node2.next = node3;
node3.next = node4;
ListNode result = swap(head);
traverse(result);
}
/**
* 虚拟节点
* 画图,不画图看不懂指针的走向
* 为什么要存节点? 只要链表的方向发生改变了如果还想使用就得提前存起来
*/
public static ListNode swap(ListNode listNode) {
ListNode header = new ListNode(-1);
header.next = listNode;
ListNode head = header;
while (head.next != null && head.next.next != null) {
ListNode temp = head.next;
ListNode temp2 = head.next.next.next;
head.next = head.next.next;
head.next.next = temp;
head.next.next.next = temp2;
head = head.next.next;
}
return header.next;
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void traverse(ListNode listNode) {
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
最后修改:2022 年 05 月 29 日 10 : 20 PM
© 允许规范转载