JAVA数据结构之——单链表的逆序

  1. package com.java.duncan;  
  2. class Node {  
  3.     public int value;  
  4.     public Node next;  
  5.     public Node() {  
  6.         value = -1;  
  7.         next = null;  
  8.     }  
  9.     public Node(int i) {  
  10.         value = i;  
  11.         next = null;  
  12.     }  
  13.     public void add(Node head, Node add) {  
  14.         Node p = head;  
  15.         if(p == nullreturn;  
  16.         while(p.next != null) {  
  17.             p = p.next;  
  18.         }  
  19.         p.next = add;  
  20.     }  
  21.     public void print(Node head) {  
  22.         Node p = head;  
  23.         if(p == null) System.out.println("链表为空!");  
  24.         while(p != null) {  
  25.             System.out.print(p.value + " ");  
  26.             p = p.next;  
  27.         }  
  28.     }  
  29.     public void reversePrint(Node node) {  
  30.         if(node.next != null) {  
  31.             reversePrint(node.next);  
  32.             System.out.print(node.value + " ");  
  33.         }  
  34.     }  
  35.       
  36.     public Node Reverse(Node head) {  
  37.         if(head==null || head.next==nullreturn head;  
  38.         Node p1 = head;  
  39.         Node p2 = head.next;  
  40.         Node p3 = p2.next;  
  41.         p1.next = null;  
  42.         while(p3 != null) {  
  43.             p2.next = p1;  
  44.             p1 = p2;  
  45.             p2 = p3;  
  46.             p3 = p3.next;  
  47.         }  
  48.         p2.next = p1;  
  49.         return p2;  
  50.     }  
  51. }  
  52.   
  53. public class ReverseList {  
  54.     public static void main(String[] args) {  
  55.         Node head = new Node();  
  56.         for(int i = 1; i <= 10; i++) {  
  57.             head.add(head,new Node(i));  
  58.         }  
  59.         head.print(head.Reverse(head));  
  60.         //System.out.println();  
  61.         //head.reversePrint(head);  
  62.           
  63.     }  
  64. }  

posted on 2013-11-06 15:33  iwant2know  阅读(79)  评论(0)    收藏  举报

导航