Android小牛算法

单链表翻转

2017-02-09  本文已影响7人  zhangxuanchen

循环

class Node{  
        int value;  
        Node next;  
    }  
      
    Node reverseList(Node head){  
        Node p1, p2, p3;  
        if(head == null || head.next == null){  
            return head;  
        }  
        p1 = head;  
        p2 = head.next;  
          
        while(p2 != null){  
            p3 = p2.next; //保存记录下一个值  
            p2.next = p1; //指向下一个点  
            p1 = p2;  
            p2 = p3;  
        }  
          
        head.next = null;  
        head = p1;  
          
        return head;  
    }  

递归

class Node{  
        int value;  
        Node next;  
}  

public Node reverse(Node head){
     if (head == null || head.next == null) return head;
     Node nextNode = head.next;
     head.next = null;
     Node reverseRest = reverse(nextNode);
     nextNode.next = head;
     return reverseRest;
 }
上一篇 下一篇

猜你喜欢

热点阅读