Microsoft interview question

Write code for Reverse linked list.

Interview Answer

Anonymous

11 Oct 2022

/** * 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) { Stack stack = new Stack(); while(head!=null){ stack.push(head.val); head = head.next; } ListNode temp,node= null; if(!stack.isEmpty()){ node =new ListNode(); node.val=stack.pop(); } temp= node; while(!stack.isEmpty()){ ListNode newNode = new ListNode(); newNode.val = stack.pop(); temp.next= newNode; temp= temp.next; } return node; } }