简体   繁体   中英

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.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM