Question: 6. Implement Linked List operations. You can not use existing List APIs. Please implement the belowing operations: (a) getSize(ListNode head): return the size of the
6. Implement Linked List operations. You can not use existing List APIs. Please implement the belowing operations: (a) getSize(ListNode head): return the size of the linked list (b) isNull(ListNode head): return true if the linked list is NULL; else false (c) display(ListNode head): print the value of each node in the linked list in order (d) insert(ListNode head, int n, int val): insert a new node to the nth position, the value of the new node equals to val.
import java.util.Random; class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class LinkedListOperations { public int getSize(ListNode head){ int size = 0; while(head!=null){ size += 1; head = head.next; } return size; } public void display(ListNode head) { if (head == null) { System.out.println(""); return; } int n = getSize(head); while (head != null) { if (n-- != 1 ) { System.out.print(head.val + "->"); head = head.next; } else { System.out.println(head.val); head = head.next; } } } public void append(ListNode head, int val) { ListNode tmp = new ListNode(val); while (head.next != null) head = head.next; head.next = tmp; return; } public void sortedAppendACS(ListNode head, int val) { ListNode tmp = new ListNode(val); if (head.val >= val) { ListNode headcopy = new ListNode(head.val); headcopy.next = head.next; head.next = headcopy; headcopy = head.next; head.val = val; return; } while (head.next != null && head.next.val <= val) head = head.next; tmp.next = head.next; head.next = tmp; return; } //Please implement other methods public static void main(String[] args){ ListNode l1 = new ListNode(2); ListNode l2 = new ListNode(4); ListNode l3 = new ListNode(6); ListNode l4 = new ListNode(7); ListNode l5 = new ListNode(8); l1.next = l2; l2.next = l3; l3.next = l4; l4.next = l5; LinkedListOperations l = new LinkedListOperations(); //l.append(l1, 12); //l.sortedAppendACS(l1, 5); l.display(l5); l.sortedAppendACS(l5, 4); l.display(l5); l.sortedAppendACS(l5, 3); l.sortedAppendACS(l5, 2); l.sortedAppendACS(l5, 1); l.display(l5); System.out.println("The size of LinkedList l1 is: " + l.getSize(l5)); //l.display(l5); //System.out.println("The size of LinkedList l5 is: " + l.getSize(l5)); //l.display(null); //System.out.println("The size of empty LinkedList is: " + l.getSize(null)); /* l.sortedAppend(l1, 6); l.sortedAppend(l1, 4); l.sortedAppend(l1, 8); l.sortedAppend(l1, 5); Random rand = new Random(); for (int i = 0; i<1000; i++) { int rnd = rand.nextInt(1000); l.sortedAppendACS(l1, rnd); //System.out.println(rnd); } l.display(l1); */ } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
