** Write a program in C ** that builds a doubly linked linked-list and populate
ID: 3606532 • Letter: #
Question
**Write a program in C** that builds a doubly linked linked-list and
populate the linked list with the integers 0 through N. The user specifies N as a command-line argument.
Note that you must trap cases where you have no command line
arguments and where you have too many command line arguments.
It is OK in both of these cases to print an error message and
exit the program.
Your program must display the value of N (formatted as shown
below - tab seperated) followed by a blank line. You may
also want to "man 3 atoi()".
As you populate the list, print out the values being inserted
(formatted as shown below - tab seperated), followed by a
blank line.
Once the list is populated, print out the contents from left
to right, then print out a blank line, then print out the
contents from right to left.
The inputs (data or payload) will simply come from a for loop
(0 to N), in that order! Here is what your output MUST look
like (except N will vary).
Command line argument: 3
Input data: 0
Input data: 1
Input data: 2
Input data: 3
Left to right output: 0
Left to right output: 1
Left to right output: 2
Left to right output: 3
Right to left output: 3
Right to left output: 2
Right to left output: 1
Right to left output: 0
Finally, pictorally, the linked list should look like this:
Head -> |---| -> |---| -> NULL
| 0 | | 1 |
NULL <- |___| <- |___| <- Tail
Explanation / Answer
public class Node { public Node next; public Object data; } public class LinkedList { private Node head; public void printAllNodes() { Node current = head; while (current != null) { Console.WriteLine(current.data); current = current.next; } } public void AddFirst(Object data) { Node toAdd = new Node(); toAdd.data = data; toAdd.next = head; head = toAdd; } public void AddLast(Object data) { if (head == null) { head = new Node(); head.data = data; head.next = null; } else { Node toAdd = new Node(); toAdd.data = data; Node current = head; while (current.next != null) { current = current.next; } current.next = toAdd; } } } class Program { static void Main(string[] args) { Console.WriteLine("Add First:"); LinkedList myList1 = new LinkedList(); myList1.AddFirst("Hello"); myList1.AddFirst("Magical"); myList1.AddFirst("World"); myList1.printAllNodes(); Console.WriteLine(); Console.WriteLine("Add Last:"); LinkedList myList2 = new LinkedList(); myList2.AddLast("Hello"); myList2.AddLast("Magical"); myList2.AddLast("World"); myList2.printAllNodes(); Console.ReadLine(); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.