Consider the following C# code that pushes nodes onto a singly linked list. What will be the printed linked list after all push operations?
public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public class LinkedList { public Node head; public void Push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } public void PrintList() { Node temp = head; while (temp != null) { System.Console.Write(temp.data + " -> "); temp = temp.next; } System.Console.WriteLine("null"); } } LinkedList list = new LinkedList(); list.Push(10); list.Push(20); list.Push(30); list.PrintList();
Remember that pushing adds a new node at the beginning of the list.
Each push inserts a new node at the head. So the last pushed node (30) becomes the first element, followed by 20, then 10.
Given the code below, what will be the printed linked list after pushing the values?
public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public class LinkedList { public Node head; public void Push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } public void PrintList() { Node temp = head; while (temp != null) { System.Console.Write(temp.data + " -> "); temp = temp.next; } System.Console.WriteLine("null"); } } LinkedList list = new LinkedList(); list.Push(5); list.Push(10); list.Push(5); list.Push(20); list.PrintList();
Push adds nodes at the front, so the last pushed value is first.
The last pushed value 20 is at the head, followed by 5, then 10, then 5.
What error will occur when running the following push method in C#?
public void Push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head.next;
head = new_node;
}Consider what happens if head is null before push.
If head is null, accessing head.next causes NullReferenceException.
Consider the push operation that inserts a new node at the beginning of a singly linked list. What is its time complexity?
Push only changes a few pointers at the head.
Push inserts at the head without traversing the list, so it takes constant time O(1).
Given the following sequence of push operations on an empty linked list, what is the final state of the list?
LinkedList list = new LinkedList(); list.Push(1); list.Push(2); list.Push(3); list.Push(4); list.Push(5); list.PrintList();
Each push adds a new node at the front, so the last pushed is first.
The list is built by adding nodes at the head, so the order is reversed from push sequence.
