Leetcode-206-Reverse Linked List

superorange 2022/07/15 362Views

Reverse Linked List

leetcode: https://leetcode.com/problems/reverse-linked-list/

Description:

Given the head of a singly linked list, reverse the list, and return the reversed list.

Idea:

**solution **

Step1: set three index, the first one is used to traverse the list and the second one is used to record result, the third one is used to store the next node in the loop as temporary node.

Step2: when the node of traversal is not null, use the temporary node to store the next node of current node(so that can continue traverse). make the next node of current node points to the previous node, so that reverse the side of linked list.

make the previous node point to current node to record result. make the current node point to temporary node to continue traversal.

Code:

/**
 * 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) {
        //set the index to traverse;
        ListNode current = head;
        //set  the previous node  to record result
        ListNode previous = null;
        //set the temp node to store the original next node
        ListNode temp = null;
        //until the end
        while(current != null){
            //temp to record the next node in the loop
            temp = current.next;
            //reverse the side of node
            current.next = previous;
            previous = current;
            //make the index point to temp to continue traverse
            current = temp;
        }
        return previous;
    }
}