反转链表

遍历法:

public class ReverseListNode {

    public ListNode Reverse(ListNode root){

        ListNode Cur = root;

        ListNode Pre = null;

        ListNode headNode =null;

        while (Cur!=null){

            ListNode next=Cur.next;

            if(next==null)

                headNode = Cur;

            Cur.next = Pre;

            Pre = Cur;

            Cur = next;

        }

        return headNode ;

    }

 

    public static void main(String[] args) {

        ListNode root=new ListNode(1);

        root.next=new ListNode(2);

        ListNode R=new ReverseListNode().Reverse(root);

    }

}

class ListNode {

 

    public int val;

    public ListNode next;

 

    public ListNode(int x) {

        val = x;

    }

}

递归实现:

package TEST.反转链表;

/**
 * Created by nick on 2018/10/9.
 */
public class reverseLinkedList {
    static ListNode reverseLinkedList(ListNode node) {
        if (node == null || node.next == null) {
            return node;
        } else {
            ListNode headNode = reverseLinkedList(node.next);
            node.next.next = node;//headNode和node是两个相交的链表
            node.next = null;
            return headNode;
        }
    }

    public static void main(String[] args) {
        ListNode root=new ListNode(1);
        root.next=new ListNode(2);
        root.next.next=new ListNode(3);
        ListNode R=reverseLinkedList(root);
    }

}

 

posted @ 2018-10-09 16:32  思考的胖头鱼  阅读(169)  评论(0编辑  收藏  举报