单链表反转(递归和非递归) (Java)

链表定义

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}
View Code

 

非递归实现很简单,只需要遍历一遍链表,在遍历过程中,把遍历的节点一次插入到头部。

public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        while(head!=null){
            ListNode tmp = head.next;
            head.next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }
View Code

 

递归实现:翻转head->为首的链表, 然后head变为尾部节点

public ListNode reverseList(ListNode head) {
        if(head==null||head.next ==null)
            return head;
        ListNode prev = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return prev;
    }
View Code

 

posted @ 2015-10-14 21:40  smile_tina  阅读(12548)  评论(0编辑  收藏  举报