package src;
import java.util.Stack;
/*
* 单链表反转
* author : Huixing Fang
*/
public class ReverseLinkedList {
static class Node {
int value;
Node next;
Node(){}
Node(int value, Node next){
this.value = value;
this.next = next;
}
}
public ReverseLinkedList() {}
//使用迭代方法
public static Node reverseite(Node head){
if (head==null) return null; // 如果传入的链表为空
else {
Node paresult = reverse(head.next); //反转除了头结点外的链表部分
head.next = null;
if (paresult==null) return head; //如果链表只有一个结点
else { //如果链表有两个以上结点
Node curr = paresult; //令curr指向除了头结点外的链表部分反转之后的链表
while(true){
if (curr.next == null) {
//找到部分反转链表的最后一个结点,让它指向原始头结点
curr.next = head;
break;//将原始头结点放入反正链表最后一个结点,然后退出循环
}
else curr = curr.next;//若还没有到最后一个结点,则继续找下一个结点
}
return paresult;//返回反转后的链表
}
}
}
//用堆栈的方式,只要遍历一遍链表,把结点依次放入堆栈中。遍历结束后,
//再从堆栈中取出结点,依次建立结点间的关系,即为反转的链表
public static Node reverse(Node head){
if (head==null) return head;
Node revhead = null;
Stack<Node> nodestack = new Stack<Node>();
while(head!=null){
//放入堆栈
nodestack.push(head);
head = head.next;
}
revhead = nodestack.pop();
Node curr = revhead;
while(true){
//从堆栈中取出结点,得到反转链表
if (nodestack.size()>0){
Node newpop = nodestack.pop();
curr.next = newpop; //依次建立关系
curr = newpop;
}
else
{//处理最后一个结点
curr.next = null;
break;
}
}
return revhead;
}
public static void printnodes(Node head){
while(head!=null){
System.out.println(head.value);
head = head.next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node head = null;
//Node head = new Node(0, null);
//Node head = new Node(0, new Node(1, null));
//Node head = new Node(0, new Node(1, new Node(2, null)));
Node result = reverse(head);
printnodes(result);
result = reverseite(head);
printnodes(result);
}
}
单链表反转
最新推荐文章于 2021-11-03 20:25:29 发布