在链表中给定节点后添加节点的 C# 程序


设置一个 LinkedList 并添加元素。

string [] students = {"Beth","Jennifer","Amy","Vera"};
LinkedList<string> list = new LinkedList<string>(students);

首先,在末尾添加一个新节点。

var newNode = list.AddLast("Emma");

现在,使用 AddAfter() 方法在给定节点后添加一个节点。

list.AddAfter(newNode, "Matt");

以下是完整代码。

示例

 实战演示

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Beth","Jennifer","Amy","Vera"};
      LinkedList<string> list = new LinkedList<string>(students);
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }

      // adding a node at the end
      var newNode = list.AddLast("Emma");

      // adding a new node after the node added above
      list.AddAfter(newNode, "Matt");

      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}

输出

Beth
Jennifer
Amy
Vera
LinkedList after adding new nodes...
Beth
Jennifer
Amy
Vera
Emma
Matt

更新于: 23-Jun-2020

230 次浏览

开启你的 职业生涯

通过完成课程获取认证

开始学习
广告
© . All rights reserved.