Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Solution: Reverse a LinkedList
Problem Statement
Given the head of a Singly LinkedList, reverse the LinkedList. Write a function to return the new head of the reversed LinkedList.
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Solution
To reverse a LinkedList, we need to reverse one node at a time. We will start with a variable current which will initially point to the head of the LinkedList and a variable previous which will point to the previous node that we have processed; initially previous will point to null.
.....
.....
.....
Like the course? Get enrolled and start learning!
Thomas MinhTu Hoang
· a year ago
// public class ListNode { // public int Val = 0; // public ListNode Next; // public ListNode(int value) { // this.Val = value; // } // } public class Solution { public ListNode reverse(ListNode head) { if (head?.Next == null) return head; ListNode fwd = head; ListNode bwd = null; while (fwd != null) { bwd = new ListNode(fwd.Val) { Next = bwd }; fwd = fwd.Next; } return bwd; }
Show 1 reply