【问题标题】:Insert node at a certain position in a linked list C++在链表C++中的某个位置插入节点
【发布时间】:2014-02-11 15:09:41
【问题描述】:

我正在尝试在某个位置插入一个节点。在我的代码中,位置为 1 的数字仅被插入(基本上在链表的开头),它没有插入位置为 2 的任何数据。 temp2 有问题吗?当我运行程序时,它并没有指向我认为的任何东西。

我知道你们多么讨厌在这里被问到作业问题,但我只是不知道我的程序有什么问题。我只是这方面的初学者,我的老师没有很好地解释链表。

代码如下。

-我得到的输出是 8 7

-我希望它读取 8 6 7 5,其中 6 和 5 插入位置 2

/*
Insert node at a given positon in a linked list.
First element in the linked list is at position 0
*/

#include<stdlib.h>
#include<stdio.h>

struct Node
{
   int data;
   struct Node* next;
};

struct Node *head;

void Insert(int data, int n)
{
   Node* temp1 = new Node();
   temp1->data = data;
   temp1->next = NULL;
   if (n == 1){
    temp1->next = head;
    head = temp1;
    return;
   }
   Node* temp2 = new Node();
   for (int i = 0; i < n-2; i++){// i feel like it doesn't even go through this loop
    temp2 = temp2->next;
   }
   temp1->next = temp2->next;
   temp2->next = temp2;
}
void print()
{
    Node* temp = head;
    while(temp != NULL){
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}
int main()
{
    head = NULL; //empty linked list
    Insert(7,1); //List: 7     
    Insert(5,2); //List: 7,5   
    Insert(8,1); //List: 8,7,5 
    Insert(6,2); //List: 8,6,7,5      
    print();
system("pause");
} 

【问题讨论】:

  • Insert函数中,首先你需要到你要插入的节点。,.​​.所以你需要Node * temp2 = head;而不是Node * temp2 = new Node();。而且,此时head可能为NULL..所以需要检查一下。

标签: c++ insert linked-list position nodes


【解决方案1】:

代码修复

/* 在链表的给定位置插入节点。 链表中的第一个元素位于位置 0 */

#include<stdlib.h>
#include<stdio.h>

struct Node
{
   int data;
   struct Node* next;
};

struct Node *head;

void Insert(int data, int n)
{
   Node* temp1 = new Node();
   temp1->data = data;
   temp1->next = NULL;
   if (n == 1){
    temp1->next = head;
    head = temp1;
    return;
   }
   Node* temp2 = head ;  //Here Only You need to assign what in head to 
                         //Pointer Variable temp2 and traverse
   for (int i = 0; i < n-2; i++){
    temp2 = temp2->next;
   }
   temp1->next = temp2->next;
   temp2->next = temp1;        // linking Whats in Temp1 To Temp2 (next)
}
void print()
{
    Node* temp = head;
    while(temp != NULL){
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}
int main()
{
    head = NULL; //empty linked list
    Insert(7,1); //List: 7     
    Insert(5,2); //List: 7,5   
    Insert(8,3); //List: 7,5,8 
    Insert(6,1); //List: 6,7,5,8   
    Insert(10,3);//List: 6,7,10,5,8 
    print();
system("pause");
} 

【讨论】:

    【解决方案2】:

    在最开始的位置插入一个元素。 列表为空时的 case-1。 case-2 当列表不为空时。

        #include<iostream>
    
    using namespace std;
    
    struct Node{
    int data;
    Node* next; //link == head =stored the address of the next node
    };
    
    Node* head;  //pointer to Head node with empty list
    
    void Insert(int y);
    void print();
    
    int main(){
        head = nullptr; //empty list
        int n,y;
        cout<<"how many number do you want to enter?"<<endl;
        cin>>n;
        for (int i=0;i<n;i++){
            cout<<"Enter the number "<<i+1<<endl;
            cin>>y;
            Insert(y);
            print();
        }
    }
    
    void Insert(int y){
        Node* temp = new Node(); //create dynamic memory allocation
        temp->data = y;
        temp->next = head; // temp->next = null; when list is empty
        head = temp;
    }
    
    void print(){
        Node* temp = head;
        cout<<"List is: "<<endl;
        while(temp!= nullptr){
            cout<<temp->data<<" ";
            temp = temp->next;
        }
        cout<<endl;
    }
    

    【讨论】:

      【解决方案3】:
      Node* insert_node_at_nth_pos(Node *head, int data, int position)
      {   
          /* current node */
          Node* cur = head;
      
          /* initialize new node to be inserted at given position */
          Node* nth = new Node;
          nth->data = data;
          nth->next = NULL;
      
          if(position == 0){
              /* insert new node at head */
              head = nth;
              head->next = cur;
              return head;
          }else{
              /* traverse list */
              int count = 0;            
              Node* pre = new Node;
      
              while(count != position){
                  if(count == (position - 1)){
                      pre = cur;
                  }
                  cur = cur->next;            
                  count++;
              }
      
              /* insert new node here */
              pre->next = nth;
              nth->next = cur;
      
              return head;
          }    
      }
      

      【讨论】:

        【解决方案4】:

        试试这个功能。

        节点对象的结构:

        class Node
        {
        private:
            int data;
            Node *next;
        
        public:
            Node(int);
            ~Node();
            void setData(int);
            int getData();
            void setNext(Node*);
            Node* getNext();
        };
        

        函数的实现:

        返回状态值始终是一种上帝的做法,此处定义的常量用于调试/记录应用程序的使用情况。

        //constants
        static int const SUCCESS = 0;
        static int const FAILURE = 1;
        static int const NULL_OBJ = 2;
        static int const POS_EXCEED = 3;
        
        int addAt(int data, int pos){
            Node *tmp = new Node(data);
            if (tmp == NULL){
                //print for debugging only.
                cout << "Object not created. Out of memory maybe" << endl;
                return NULL_OBJ;
            }
            if (pos == 0){
                // add at beginning
                tmp->setNext(this->head);
                this->head = tmp;
                return SUCCESS;
            }else{
                // add element in between or at end
                int counter = 1;
                Node* currentNode = this->head;
                while (counter < pos && currentNode->getNext() != NULL){
                    currentNode= currentNode->getNext();
                    counter++;
               }
               tmp->setNext(currentNode->getNext());
               currentNode->setNext(tmp);
               return SUCCESS;
           }
           cout << "Failed due to unknown reason.";
           return FAILURE;
        }
        

        这里的假设是,您将在验证输入(数据和位置)后调用该函数。虽然我们可以验证函数内部的参数,但这不是一个好习惯。

        希望这会有所帮助。

        【讨论】:

          【解决方案5】:
           void addToSpecific()
           {
           int n;   
           int f=0;   //flag
           Node *temp=H;    //H-Head, T-Tail
           if(NULL!=H)  
           {
              cout<<"Enter the Number"<<endl;
              cin>>n;
              while(NULL!=(temp->getNext()))
              {
                 if(n==(temp->getInfo()))
                 {
                f=1;
                break;
                 }
                 temp=temp->getNext();
              }
           }
           if(NULL==H)
           {
              Node *nn=new Node();
              nn->setInfo();
              nn->setNext(NULL);
              T=H=nn;
           }
           else if(0==f)
           {
              Node *nn=new Node();
              nn->setInfo();
              nn->setNext(NULL);
              T->setNext(nn);
              T=nn;
           }
           else if(1==f)
           {
              Node *nn=new Node();
              nn->setInfo();
              nn->setNext(NULL);
              nn->setNext((temp->getNext()));
              temp->setNext(nn);
           }
           }
          

          【讨论】:

          • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
          【解决方案6】:

          只要有这样的东西,你就可以遍历到给定的位置,然后插入:

          void addNodeAtPos(int data, int pos)
          {
            Node* prev = new Node();
            Node* curr = new Node();
            Node* newNode = new Node();
            newNode->data = data;
          
            int tempPos = 0;   // Traverses through the list
          
            curr = head;      // Initialize current to head;
            if(head != NULL)
            {
              while(curr->next != NULL && tempPos != pos)
              {
                  prev = curr;
                  curr = curr->next;
                  tempPos++;
              }
              if(pos==0)
              {
                 cout << "Adding at Head! " << endl;
                 // Call function to addNode from head;
              }
              else if(curr->next == NULL && pos == tempPos+1)
              {
                cout << "Adding at Tail! " << endl;
                // Call function to addNode at tail;
              }
              else if(pos > tempPos+1)
                cout << " Position is out of bounds " << endl;
               //Position not valid
          
              else
              {
                  prev->next = newNode;
                  newNode->next = curr;
                  cout << "Node added at position: " << pos << endl;
              }
           }
           else
           {
              head = newNode;
              newNode->next=NULL;
              cout << "Added at head as list is empty! " << endl;
           }
          }
          

          【讨论】:

            【解决方案7】:
            Node* InsertNth(int data, int position)
            {
              struct Node *n=new struct Node;
              n->data=data;  
              if(position==0)
              {// this will also cover insertion at head (if there is no problem with the input)
            
                  n->next=head;
                  head=n;
              }
            
              else
              {
                  struct Node *c=new struct Node;
                  int count=1;
                  c=head;
                  while(count!=position)
                  {
                      c=c->next;
                      count++;
                  }
                  n->next=c->next;
                  c->next=n;
            
              }
                return ;
            }
            

            【讨论】:

              【解决方案8】:

              我和你一样在插入过程中遇到了一些问题,所以这是我解决问题的代码:

              void add_by_position(int data, int pos)
                {
                      link *node = new link;
                      link *linker = head;
              
                      node->data = data;
                      for (int i = 0; i < pos; i++){
                          linker = linker->next;
                      }
                      node->next = linker;
                      linker = head;
                      for (int i = 0; i < pos - 1; i++){
                          linker = linker->next;
                      }
                      linker->next = node;
                      boundaries++;
                  }
              

              【讨论】:

                【解决方案9】:

                要在特定位置插入k,您需要遍历列表直到位置k-1,然后进行插入。

                [您不需要像在代码中那样创建一个新节点来遍历该位置]您应该从头节点开始遍历。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-12-11
                  • 1970-01-01
                  • 2022-10-18
                  • 1970-01-01
                  • 2021-04-28
                  相关资源
                  最近更新 更多