标签:style blog color os ar for sp div log
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 = 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-
标签:style blog color os ar for sp div log
原文地址:http://www.cnblogs.com/xiejc/p/4054823.html