在链表中的某个位置插入节点 C

新手上路,请多包涵

我试图在某个位置插入一个节点。在我的代码中,位置为 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");
}

原文由 Raslion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
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");
}

原文由 Bilal Mohmand 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题