反转单链表的意思就是
原来单链表的值为1>2>3>4>5
反转之后会变成5>4>3>2>1
我们需要了解的是一定不能重新创建一个单链表来进行反转,因为那样太简单了,并且是极度浪费空间和资源的,有时候实在oj上跑不过的
首先我将单链表的有关代码放在这里
import com.sun.deploy.net.proxy.ProxyUnavailableException;
class Node {//节点类
public int data;
public Node next;
public Node() {
}
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class SingleLinkedList {
//单链表本身是一种类
//由节点来构成单链表,
public Node head;//头节点
public SingleLinkedList() {
this.head = null;
}
//头插法
public void addFirst(int data) {
Node node = new Node(data);
if(this.head == null) {
this.head = node;
return;
}
node.next = this.head;
this.head = node;
}
//打印单链表
public void display() {
Node cur = this.head;
if(this.head == null) {
System.out.println("没有存放数据");
}
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
}
public void display2(Node newHead) {
Node cur = newHead;
if(this.head == null) {
System.out.println("没有存放数据");
}
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
}
}
第一种方法我们可以用定义三个节点来进行反转,反转完之后可以利用display2进行打印
public Node reverseSingleLinkList() {
//反转一个单链表,遍历一次
Node cur = this.head;
if(cur == null) {
return null;
}
if(cur.next == null) {
return cur;
}
Node prev = null;
Node newHead = null;
while(cur != null) {
Node curNext = cur.next;
if(cur.next == null) {
newHead = cur;
}
cur.next = prev;
prev = cur;
cur = curNext;
}
return newHead;
}
第二种方法我们利用头插法进行打印
public Node reverseSingleLinkList2() {
//利用头插法来反转单链表
if(this.head == null) {
return null;
}
if(this.head.next == null) {
return this.head;
}
Node node = this.head.next;
this.head.next = null;
while (node != null ) {
addFirst(node.data);
node = node.next;
}
return this.head;
}
本文详细介绍了两种单链表反转的方法:通过定义三个节点进行反转及利用头插法实现。文章提供了完整的代码示例,深入解析了每一步操作,帮助读者理解单链表反转的原理和实践。
1405

被折叠的 条评论
为什么被折叠?



