public void InsertHead(myLinkedlist list, int data) { Node newNode = new Node(data); newNode.next = list.head; list.head = newNode; }
public void printAllNodes(myLinkedlist list) { Node current = head; while (current != null) { Console.WriteLine(current.data); current = current.next; } }
public Node GetTail(myLinkedlist list) { Node temp = list.head; while (temp.next != null) { temp = temp.next; } return(temp); }
public void InsertTail(myLinkedlist list, int data) { Node newNode = new Node(data); if (list.head == null) { list.head = newNode; return; } Node lastNode = GetTail(list); lastNode.next = newNode; }
public void Reverse(myLinkedlist list) { Node prev = null; Node current = list.head; Node temp = null; while (current != null) { temp = current.next; current.next = prev; prev = current; current = temp; } list.head = prev; }
public void InsertAfter(myLinkedlist list, int numNode, int data) { Node temp = list.head; int i = 1; while (i != numNode - 1 && temp != null) { temp = temp.next; i++; } Node newNode = new Node(data); newNode.next = temp.next; temp.next = newNode; }
static void Main(string [] args) { Console.WriteLine("How many nodes do you want to add?"); myLinkedlist myList = new myLinkedlist(); string response = Console.ReadLine(); int num = Int32.Parse(response); myList.InsertHead(myList, 1); int i; for (i = 1; i < num; i++) { myList.InsertTail(myList, i + 1); } Console.WriteLine("The list:"); myList.printAllNodes(myList); Console.WriteLine("Adding the node to the head"); myList.InsertHead(myList, ++i); Console.WriteLine("The list:"); myList.printAllNodes(myList); Console.WriteLine("Where do you want to add the node?"); string response2 = Console.ReadLine(); int num2 = Int32.Parse(response2); myList.InsertAfter(myList, num2, ++i); Console.WriteLine("The list:"); myList.printAllNodes(myList); Console.WriteLine("Deleting the head:"); myList.DeleteNode(myList, num + 1); Console.WriteLine("The list:"); myList.printAllNodes(myList); Console.WriteLine("Deleting the last added node:"); myList.DeleteNode(myList, i); Console.WriteLine("The list:"); myList.printAllNodes(myList); Console.WriteLine("Reversing the list:"); myList.Reverse(myList); Console.WriteLine("The list:"); myList.printAllNodes(myList); Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
public void DeleteNode(myLinkedlist list, int key) { Node temp = list.head; Node prev = null; if (temp != null && temp.data == key) { list.head = temp.next; return; } while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } if (temp == null) { return; } prev.next = temp.next; }