算法学习之二: 链表逆序

链表的定义,链表包括两个部分,数据data 和下一个节点 next

class Node{  
    int data;  
    Node next;  
      
    public Node(int data){  
        this.data = data;  
    }   
}

链表逆序:

//链表逆序
    public Node Reverse(Node head) {  
        if(head==null || head.next==null) return head;  
        Node p1 = head;  
        Node p2 = head.next;  
        Node p3 = p2.next;  
        p1.next = null;  
        while(p3 != null) {  
            p2.next = p1;  
            p1 = p2;  
            p2 = p3;  
            p3 = p3.next;  
        }  
        p2.next = p1;  
        return p2;  
    }  

这样就可以起到逆序的结果,为了测试方便,增加了添加节点和打印:

class Node{  
    int data;  
    Node next;  
      
    public Node(int data){  
        this.data = data;  
    }   
    
    //添加节点
    public void add(Node head, Node add) {  
        Node p = head;  
        if(p == null) return;  
        while(p.next != null) {  
            p = p.next;  
        }  
        p.next = add;  
    }  
    //打印
    public void print(Node head) {  
        Node p = head;  
        if(p == null) System.out.println("链表为空!");  
        while(p != null) {  
            System.out.print(p.data + " ");  
            p = p.next;  
        }  
    }  
    public void reversePrint(Node node) {  
        if(node.next != null) {  
            reversePrint(node.next);  
            System.out.print(node.data + " ");  
        }  
    }  
      
    //链表逆序
    public Node Reverse(Node head) {  
        if(head==null || head.next==null) return head;  
        Node p1 = head;  
        Node p2 = head.next;  
        Node p3 = p2.next;  
        p1.next = null;  
        while(p3 != null) {  
            p2.next = p1;  
            p1 = p2;  
            p2 = p3;  
            p3 = p3.next;  
        }  
        p2.next = p1;  
        return p2;  
    }  
}  

全部代码如上。

你可能感兴趣的:(算法学习之二: 链表逆序)