单链表翻转

作者: zhangxuanchen | 来源:发表于2017-02-09 19:57 被阅读7次

    循环

    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;
     }
    

    相关文章

      网友评论

        本文标题:单链表翻转

        本文链接:https://www.haomeiwen.com/subject/vcewittx.html