Chaitanya GaneshRaju
Chaitanya GaneshRaju

Reputation: 41

Elements are not inserting properly while creating a linked list in c#

I have the node structure like this for singly-linked list.

public class ListNode {
      public int val;
      public ListNode next;
      public ListNode(int val=0, ListNode next=null) {
          this.val = val;
          this.next = next;
      }
 }

I am trying to create a liked list like this

//requiredDigit = 123456

ListNode finalNode = new ListNode();
        
for(int i=0; i < requiredDigit.Length; i++){
        finalNode.val =  requiredDigit[i] - '0';
        finalNode.next =  new ListNode();
}

Whenever I try this kind of approach the list is being created as 60, the first element is being missed.

Upvotes: 0

Views: 46

Answers (1)

MoonMist
MoonMist

Reputation: 1227

The issue here is that you're not moving to the next node in the linked list chain. Currently your solution doesn't change the value of finalNode; it stays on the same instance and nothing progresses, so you end up just overriding the starting node. the val value goes from 1 to 2 to 3, etc, but all in the same node.

This is a potential solution. I'm sure there's a more elegant one, but this works:

ListNode startNode = null, finalNode = null, iterNode;

for(int i=0; i < requiredDigit.Length; i++)
{
    if (startNode == null)
    {
        startNode = new ListNode(requiredDigit[i] - '0');
        finalNode = head;
    }
    else if (finalNode.next == null)
    {
        finalNode.next = new ListNode(requiredDigit[i] - '0');
        finalNode = finalNode.next;
    }
}

Upvotes: 1

Related Questions