简体   繁体   English

在 c# 中创建链表时元素未正确插入

[英]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.每当我尝试这种方法时,列表都被创建为60 ,第一个元素就被遗漏了。

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 ;目前您的解决方案不会更改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. val值从 1 到 2 再到 3,等等,但都在同一个节点中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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