在链接列表的特定位置插入节点 [英] Inserting a node at a specific position in a Linked list

查看:101
本文介绍了在链接列表的特定位置插入节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为我提供了指向链表头节点的指针,要添加到链表的整数以及必须插入该整数的位置。
在需要的位置插入此节点后,我需要返回头节点。

I am given the pointer to the head node of a linked list, an integer to add to the list and the position at which the integer must be inserted. After inserting this node at the desired position I need to return the head node.

由于某些原因,我编写的代码无法正常工作并进入无限循环

The code that I have written is not working for some reason and goes in an infinite loop.

  class Node {
     int data;
     Node next;
  }


Node InsertNth(Node head, int data, int position) {
    int count = 0;
    Node node = head;
    Node prev = null;
    while(count != position){
      count++;
      node = node.next;
      prev = node;
    }

    Node newNode = new Node();
    newNode.data = data;


    newNode.next = node;
    if(count == 0){
          head = newNode;
       }else{
          prev.next = newNode;
    }

    return head;          
}


推荐答案

node = node.next;
prev = node;

此顺序应相反

prev = node;
node = node.next;

而且代码也不会检查很多情况,例如关于指定位置是否更大比链表的大小大。尝试重写代码,也可以提及您要使用哪些值来测试功能。
我认为 prev = node 应该抛出异常,因为prev尚未初始化

And also the code does not check for many cases , for example as to whether the position specified is larger than the size of the linked list. Try rewriting the code , also could you mention which values are you using for testing the function. I think prev=node should throw an exception as prev was not initialized

这篇关于在链接列表的特定位置插入节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆