Define a function that takes the head node of a linked list, reverses the list, and outputs the head node of the reversed list.
Example: input: 1 – > 2 – > 3 – > 4 – > 5 – > NULL output: 5 – > 4 – > 3 – > 1 – > 2 – > NULL
Source: LeetCode link: leetcode-cn.com/problems/fa… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Implementation idea: disconnect the current linked list nodes one by one and insert them into the new linked list with the head plug method
Code implementation:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; }} * * /
class Solution {
public static ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode L = new ListNode();
L.next = null; // Add a header
ListNode temp;
while(head! =null){
temp = head.next; // Save the next node
head.next = L.next; // Insert the current node into L
L.next = head;
head = temp;
}
returnL.next; }}Copy the code