206.Reverse Linked List(单链表逆置)

来源:互联网 发布:非农就业数据公布 编辑:程序博客网 时间:2024/06/06 07:38

Reverse a singly linked list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }  
 **/
 
 方法一:递归实现

public class Solution {
    public ListNode reverseList(ListNode head) {
            if(head == null||head.next==null) return head;
            ListNode nextNode = head.next ;
            ListNode newHead = reverseList(head.next);
            nextNode.next = head ;
            head.next = null;
            return newHead;
    }
}

方法二:非递归

public class Solution {
    public ListNode reverseList(ListNode head) {

    if(head == null||head.next==null) return head;
    ListNode prev = head;
    ListNode temp = prev.next;
    while(temp != null){
        ListNode next = temp.next;
        temp.next = prev;
        prev = temp;
        temp = next;
    }
    head.next = null;
    return prev;
 }

}

0 0
原创粉丝点击