反轉鏈表_Java實現

反轉鏈表:

將鏈式存儲的鏈表反轉,如原始鏈表爲:head->node1->node2->node3...->tail,

反轉後爲taill->...node3->node2->node1->head.

我分別用了非遞歸和遞歸的方法實現,java代碼如下:

Node.java

public class Node {
public char data;
public Node next;
public Node(char data, Node next)
{
this.data = data;
this.next = next;
}
public Node(char data)
{
this.data = data;
this.next = null;
}
}

ReverseLinkedList.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReverseLinkedList {
private Node head;
private Node tail;
public ReverseLinkedList() {
this.head = null;
this.tail = null;
}
public boolean isEmpty() {
return (this.head == null);
}
public void CreateLinkedList() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
Node node = null;
char data;
try {
str = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
for(int i=0; i<str.length(); i++) {
data = str.charAt(i);
if(data != ' ') {
node = new Node(data);
if(i==0) {
head = node;
tail = node;
}
else {
tail.next = node;
tail = node;
}
}
}
}
public void PrintLinkedList() {
System.out.print("Head");
Node node = this.head;
while(node!=null) {
System.out.print("->" + node.data);
node = node.next;
}
System.out.println("->Tail");
}
//反轉鏈表,非遞歸方法
public void ReverseIt() {
if(isEmpty()) return ;
Node previous=null;
Node current = this.head;
Node next = this.head.next;
while(true) {
current.next = previous;
previous = current;
if(previous == this.tail) break;
current = next;
next = next.next;
}
tail = head;
head = previous;
}
//反轉鏈表,遞歸方法實現
public Node ReverseIt(Node node) {
if(node==null || node==tail) return node;
Node next = ReverseIt(node.next);
next.next = node;
return node;
}
public void Reverse() {
Node tempt = ReverseIt(this.head);
head = tail;
tail = tempt;
if(tail!=null) tail.next = null;
}
}

TestDriver.java

public class TestDriver {
public static void main(String arg[]) {
ReverseLinkedList forTest = new ReverseLinkedList();
forTest.CreateLinkedList();
forTest.PrintLinkedList();
forTest.ReverseIt();
forTest.PrintLinkedList();
forTest.Reverse();
forTest.PrintLinkedList();
}
}

控制檯下的運行如例子:

135602894.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章