三种方式实现单链表的逆序,分别是头结点插入,对称交换和利用堆栈来实现。三种方式分别是出于空间和时间的考虑来实现的,详见注释。
public class LinkedList {
class Node {
private Node next;
private Object data;
public Node() {
super();
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
private Node head;
public Node first() {
return head.next;
}
public Node tail() {
Node temp = head;
while (temp.next != null)
temp = temp.next;
return temp;
}
public Node head() {
return head;
}
public LinkedList() {
head = new Node(null, null);
}
public boolean addStack(Object data, Node head) {
boolean flag = false;
Node node = new Node(data, null);
if (!flag) {
node.next = head.next;
head.next = node;
flag = true;
}
return flag;
}
public boolean addQueue(Object data, Node head) {
Node temp = head;
while (temp.next != null)
temp = temp.next;
boolean flag = false;
Node node = new Node(data, null);
if (!flag) {
temp.next = node;
flag = true;
}
return flag;
}
public void print(Node head) {
Node temp = head;
while (temp.next != null) {
System.out.println("list node data :" + temp.data);
temp = temp.next;
}
System.out.println("list node data :" + temp.data);
}
public void addQueue() {
}
//直接头结点插入
public LinkedList invertedList(Node head) {
LinkedList newList = new LinkedList();
Node temp = head;
while (temp.next != null) {
addStack(temp.data, newList.head);
temp = temp.next;
}
addStack(temp.data, newList.head);
return newList;
}
public int length() {
Node temp = head;
int i = 0;
while (temp.next != null) {
i++;
temp = temp.next;
}
return i;
}
//交换两个对应的数据来实现,链表逆序
public void invertedListExchange(Node head) {
Node tempStart = head;
Object old = null;
Node tempEnd = null;
int halfLen = this.length() / 2;
for (int i = 0; i < halfLen; i++) {
tempEnd = tempStart;
if (i == 0) {
tempEnd = this.tail();
}
while (i != 0 && tempEnd.next.data != old)
tempEnd = tempEnd.next;
System.out.println(tempStart.data);
Object tt = tempStart.data;
tempStart.data = tempEnd.data;
tempEnd.data = tt;
old = tempEnd.data;
tempStart = tempStart.next;
}
}
//利用栈的性质来实现
public LinkedList invertedListByStack(Node head) {
Deque<Object> stack = new java.util.LinkedList<Object>();
Node temp = head;
while (temp.next != null) {
stack.push(temp.data);
temp = temp.next;
}
stack.push(temp.data);
LinkedList newList = new LinkedList();
Node node = newList.head;
while (!stack.isEmpty()) {
addQueue(stack.pop(), node);
}
return newList;
}
}