Skip to content

Latest commit

 

History

History
69 lines (52 loc) · 1.46 KB

20210124.md

File metadata and controls

69 lines (52 loc) · 1.46 KB

Algorithm

206. Reverse Linked List

Description

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

  • A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head){
        // 如果节点为空或者只有一个元素直接返回即可
        if(head == null || head.next == null){
            return head;
        }
        // 定义前节点
        ListNode pre = null;
        // 定义当前节点
        ListNode now = head;
        // 如果当前节点不为空,继续遍历
        while(now!=null){
            // 先定义临时变量保存下一个节点
            ListNode next = now.next;
            // 当前节点的下一个节点指向pre,这样实现了当前节点的反转
            now.next = pre;
            // 同时当前节点指向now,表示后移一位
            pre = now;
            // now节点指向next,同样后移一位
            now = next;
        }
        return pre;
    }
}

Discuss

Review

Tip

Share