我在理解這段代碼的某些部分時遇到了問題...
我猜這是關于如何通過參考存盤值,我的問題主要是關于方法: InsertDataAtTheEnd :我無法理解變數 temp 如何影響變數頭,因為它被while回圈越來越多地截斷了......最后是影響頭部的temp.next的分配。類似的情況發生在方法 DelteNodeByValue 中。
有人可以向我解釋一下,或者展示一些材料,可以簡單地解釋這里發生的事情嗎?:(
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp8
{
class SinglyLinkedList
{
public Node head { get; set; }
public void InsertDataAtTheBeggining(int data)
{
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void InsertDataAtTheEnd(int data)
{
Node temp = head;
while (temp.next != null)
{
temp = temp.next;
}
Node newNode = new Node(data);
// Node lastElement = GetLastElement(this);
temp.next = newNode;
}
Node GetLastElement(SinglyLinkedList List)
{
Node temp = head;
while (temp.next != null)
{
temp = temp.next;
}
return temp;
}
void DelteNodeFromEnd()
{
Node lastElement = GetLastElement(this);
}
public void DelteNodeByValue(int value)
{
var temp = head;
Node previusly = null;
if (temp != null && temp.data == value) // w przypadku jesli chce sie usunac pierwszy element listy;
{
head = temp.next;
return;
}
while (temp != null && temp.data != value)
{
previusly = temp;
temp = temp.next;
}
if (temp == null)
{
return;
}
previusly.next = temp.next;
}
public void DelteNodeFromBeggining()
{
head = head.next;
}
public void ShowAllData()
{
Node holder = head;
while (holder != null)
{
Console.WriteLine(holder.data);
holder = holder.next;
}
}
internal class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
}
}
uj5u.com熱心網友回復:
就我個人而言,我不會像那樣在 C# 中實作鏈表(我認為代碼中也有幾個錯誤)。考慮到 System.Collections.Generic 中內置的通用雙向鏈表結構 LinkedList 和 LinkedListNode,可能根本不是。盡管如此,了解幕后的概念確實很重要,因此我將嘗試為您解釋有問題的代碼段。
InsertDataAtEnd() 方法由幾個步驟組成:
1.
Node temp = head;
head 表示對鏈表中第一個節點的參考。當我們將 temp 宣告為 head 時,我們實際上在做的是將 temp 設定為對串列第一個節點的另一個參考。即, head 和 temp 現在都指向串列的第一個節點。它們指向記憶體中的同一個位置。例如,對于值為 5->7->4->2 的鏈表:

2.
while (temp.next != null)
{
temp = temp.next;
}
我們提前 temp 指向串列的最后一個元素。我們通過使用最后一個元素的下一個屬性為空這一事實來實作這一點。因此,我們前進指標,直到它指向的節點的下一個屬性為空。
所以在這個階段之后 head 仍然指向串列的第一個節點和 next 指向串列的最后一個元素。
這兩個階段在您的 GetLastElement() 方法中基本相同。3.
Node newNode = new Node(data);
temp.next = newNode;
We create a new node with the specified data, and declaring the next attribute of temp to point at that new node. Since temp points at the last element, its next attribute was null, and now it the new element. So the new node has now become the last element.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350272.html
