單鏈表反轉

public class ListReverse {
     public static void main(String[] args){
          Node d = new Node("d", null);
          Node c = new Node("c", d);
          Node b = new Node("b", c);
          Node a = new Node("a", b);
          Node head = a;
          System.out.print("排序前:");
          while(head != null){
              System.out.print(head.getData() + " ");
              head = head.getNext();
          }
          //head = resverse1(a);
          head = resverse2(a);
          System.out.print("\n" + "排序後:");
          while(head != null){
              System.out.print(head.getData() + " ");
              head = head.getNext();
          }
     }
     /*
      * 遞歸實現
      * 從後向前修改指針指向
      */
    private static Node resverse1(Node head) {
        if (head == null || head.getNext() == null) {
            return head;
        }
        Node reHead = resverse1(head.getNext());// 先反轉後續節點head.getNext()
        head.getNext().setNext(head);// 將當前結點的指針域指向前一結點
        head.setNext(null);// 前一結點的指針域令爲null;
        return reHead;// 反轉後新鏈表的頭結點node

    }
    
    /*
     * 非遞歸實現
     * 從前向後修改指針指向
     */
    private static Node resverse2(Node head) {
        if(head == null) {
            return head;
        }
        Node pre = null;
        Node cur = head;
        Node temp = null;
        while (cur != null) {
            temp = cur.getNext();
            cur.setNext(pre);
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}    this

class Node{
    private String data;
    private Node next;
    public Node(String data){
        this.data = data;
    }
    public Node(String data, Node next){
        this.data = data;
        this.next = next;
    }
    public void setNext(Node node){
        this.next = node;
    }
    public Node getNext(){
        return next;
    }
    public void setData(String data){
        this.data = data;
    }
    public String getData(){
        return data;
    }
}.net

 

//遞歸實現參考 http://blog.csdn.net/guyuealian/article/details/51119499指針

相關文章
相關標籤/搜索