使用java将一个单链表逆序输出
例: 未逆序前: 0 1 2 3 4 5 6 7 8 9 10 11
逆序后: 11 10 9 8 7 6 5 4 3 2 1 0
代码:
ReverseLinkList:
public class ReverseLinkList {
public static void main(String[] args) {
Node<Integer> curr = null;
// 插入数据
curr = insertData();
printNodeListData(curr);
System.out.println();
curr = reverse(curr);
printNodeListData(curr);
print("\n---------------------------");
}
/**
* 插入节点数据
*
* @return
*/
private static Node<Integer> insertData() {
Node<Integer> curr, tail;
curr = tail = new Node<Integer>(0);
for (int i = 1; i < digitList.size(); i++) {
Node<Integer> newNode = new Node<Integer>(i);
tail.next = newNode;
tail = newNode;
}
return curr;
}
/**
* 打印节点列表
*
* @param nodeList
*/
private static void printNodeListData(Node<Integer> nodeList) {
Node<Integer> temp = nodeList;
while (temp != null) {
print(temp.data + " ");
temp = temp.next;
}
}
/**
* 打印数据
*
* @param data
*/
private static <T> void print(T data) {
System.out.print(data);
}
private static <T> Node<T> reverse(Node<T> curr) {
// 当链表为空,或链表没有元素
if (curr == null || curr.next == null) {
return curr;
}
Node<T> next = null;
Node<T> prev = null;
while (curr != null) {
next = curr.next; // 保存当前节点的下一个节点
curr.next = prev; // 把上一个节点赋值给当前节点的下一个节点
prev = curr; // 把当前节点赋值为上一个节点
curr = next; // 把当前的节点替换为 保存当前节点的下一个节点
}
return prev;
}
}
Node:
public class Node<T> {
public T data;// 节点数据
public Node next; //该节点指向下一个节点的指针
public Node(T data) {
super();
this.data = data;
this.next = null;
}
}