首页 > 代码库 > 单链表反转
单链表反转
package xie.struct;public class LinkedList { public static void main(String[] args) { LinkedList list=new LinkedList(); for(int i=0;i<15;i++) { list.AddData(i); } System.out.println("初始化链表"); list.toString(); System.out.println(); System.out.println("递归反转链表"); list.Reserve(list.getHead().next); list.toString(); System.out.println(); System.out.println("常规反转链表"); list.Reserve2(); list.toString(); } public class Node{ int data; Node next; public Node() { } public int getData() { return data; } public void setData(int data) { this.data =http://www.mamicode.com/ data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } } private Node head; public LinkedList() { head=new Node(); head.data=-1; head.next=null; } public void AddNode(Node node) { Node pNode=head; while(pNode.next!=null) { pNode=pNode.next; } pNode.next=node; return; } public void AddData(int data) { Node newnode=new Node(); newnode.data=data; newnode.next=null; Node pNode=head; while(pNode.next!=null) { pNode=pNode.next; } pNode.next=newnode; return; } public Node Reserve(Node node) { if(node.next==null) { this.head.next=node; return node; } Node pre=Reserve(node.next); pre.next=node; node.next=null; return node; } public void Reserve2() { Node node=this.head.next; Node p=node.next; Node current; while(p!=null) { current=p; p=current.next; current.next=this.head.next; this.head.next=current; } node.next=null; } public String toString() { Node pNode=head.next; while(pNode!=null) { System.out.print(pNode.data+"-"); pNode=pNode.next; } return null; } public Node getHead() { return head; } public void setHead(Node head) { this.head = head; }}
初始化链表
0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-
递归反转链表
14-13-12-11-10-9-8-7-6-5-4-3-2-1-0-
常规反转链表
0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-
单链表反转
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。