In: Computer Science
Write java code to reverse a linked list. Fill in reverseLists()
ReverseLinkedList.java
package mid;
public class ReverseLinkedList {
private static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void printList(ListNode l1) {
ListNode cur = l1;
while(cur != null) {
System.out.println(cur.val);
cur = cur.next;
}
}
public static ListNode reverseLists(ListNode h1) {
}
public static void main(String[] args) {
ListNode l1_4 = new ListNode(4);
ListNode l1_3 = new ListNode(3, l1_4);
ListNode l1_2 = new ListNode(2, l1_3);
ListNode l1_1 = new ListNode(1, l1_2);
ListNode h1 = l1_1;
System.out.println("list is:");
printList(h1);
ListNode h2 = reverseLists(h1);
System.out.println("Reversed list is:");
printList(h2);
}
}
public class Main {
private static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
//to diplay the list
public static void printList(ListNode l1) {
ListNode cur = l1;
while(cur != null) {//iterating until null value
System.out.println(cur.val);//printing node value
cur = cur.next;
}
}
//-----------------------------------------------------------
//reversing the list by sending the header as parameter to it
public static ListNode reverseLists(ListNode h1)
{
ListNode prev = null;
ListNode current = h1;
ListNode next =
null;
while (current != null)
{ //iterating until null
//swaping the nodes in list
next = current.next;
current.next = prev;
prev = current;
current = next;
}
h1= prev;
return h1; //returning
the header
}
//-------------------------------------------------------------------------
public static void main(String[] args) {
//CREATING LINKED LIST
ListNode l1_4 = new ListNode(4);
ListNode l1_3 = new ListNode(3, l1_4);
ListNode l1_2 = new ListNode(2, l1_3);
ListNode l1_1 = new ListNode(1, l1_2);
ListNode h1 = l1_1;
System.out.println("list is:");
printList(h1);
ListNode h2 = reverseLists(h1);
System.out.println("Reversed list is:");
printList(h2);
}
}
. Fill in reverseLists()