Java 实现反转一个链表
class MySingleNodeTest {
static class ListNode{
public int value;//数据
public ListNode next;//地址
public ListNode(int value) {
this.value = value;
}
}
//设置头结点
public ListNode head;
//创建链表
public void createNode() {
ListNode listNode1 = new ListNode(12);
ListNode listNode2 = new ListNode(23);
ListNode listNode3 = new ListNode(34);
ListNode listNode4 = new ListNode(45);
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
this.head = listNode1;//设置头结点
}
// 打印链表
public void disPlay() {
ListNode cur = this.head;
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;//cur指向它的下一个
}
System.out.println();//换行
}
// 反转一个链表
public ListNode reversalList() {
// 如果链表是空的
if (this.head == null) {
return null;
}
// 如果只有一个结点不需要反转
if (this.head.next == null) {
return this.head;
}
// 创建一个 cur 指向头结点的后一个结点
ListNode cur = this.head.next;
// 将头结点置为空
this.head.next = null;
// 开始四个步骤移动 cur 和后面的结点
while (cur != null) {
ListNode curNext = cur.next;
cur.next = this.head;
head = cur;
cur = curNext;
}
// 循环结束反转完成返回头结点即可
return this.head;
}
}
public class MySingleNode {
public static void main(String[] args) {
MySingleNodeTest mySingleNodeTest = new MySingleNodeTest();
// 调用方法创建链表
mySingleNodeTest.createNode();
// 打印反转之前的链表
mySingleNodeTest.disPlay();
// 调用反转方法反转
mySingleNodeTest.reversalList();
// 打印反转之后的链表
mySingleNodeTest.disPlay();
}
}