LeetCode 206. Reverse Linked List

2018-10-29 17:04:40 浏览数 (1)

206. Reverse Linked List

Reverse a singly linked list.

Example:

代码语言:javascript复制
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

解法一:

代码语言:javascript复制
public ListNode reverseList(ListNode head) {
    if (head == null || head.next ==null) return head;
    ListNode pre = null;
    ListNode cur = head;
    ListNode next = head.next;
    while (cur !=null&&next !=null){
        cur.next = pre;
        pre = cur;
        cur = next;
        next = next.next;
    }
    cur.next = pre;
    return cur;
}

解法二:

这个解法与解法一的区别在于对next何时进行更新,如何更新。

代码语言:javascript复制
public ListNode reverseList(ListNode head) {
    if (head == null || head.next ==null) return head;
    ListNode pre = null;
    ListNode cur = head;
    ListNode next;
    while (cur !=null){
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

注意细节的处理。

扩展:反转双向链表

0 人点赞