且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单个链表中的任何索引处插入新节点

更新时间:2023-11-30 19:57:22

如下图所示,需要在两个节点之间插入节点.

As you can see in the image below, you need to insert the node between two nodes.

另外三个案例是

  • 在列表开头插入
  • 在列表中间插入
  • 在列表末尾插入.

维护一个计数并遍历列表中的所有元素.这个数将帮助您跟踪索引.

Maintain a count and loop through all the elements in the list. This count will help you keep track of the index.

到达节点后,必须在其中插入新节点

Once you reach the node, where you have to insert the new node

  • 创建新节点
  • 将上一个节点的下一个指针指向新节点.
  • 将新节点的下一个指针指向当前节点.

完整源代码可用这里