Insert a Node at the Tail of a Linked List

  • + 0 comments

    Here is my csharp solution:

    static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {
            
            SinglyLinkedListNode curr = head;
            SinglyLinkedListNode n1 = new SinglyLinkedListNode(data);
            
            if(head == null)
            {
                head = n1;
                Console.WriteLine(head.data);
            }
            else
            {
                if(curr.next == null)
                    head.next = n1;
                else
                {
                    while(curr.next != null)
                        curr = curr.next;
                    
                    curr.next = n1;
                }
                Console.WriteLine(head.next.data);
            }
            
            return head;
        }