C语言 关于向链表插入元素的问题

C语言 关于向链表插入元素的问题,第1张

因为你insert函数只是传进head的值,只是值传递,不能对head本身进行修改,只能对head->next以及后面的内容进行修改。

用二级指针,就可以改head了

#include<iostream>

using namespace std

struct Node

{

     int num

     Node *next

}

Node * create()

{

     Node *head,*p1,*p2

     p1 = new Node

     cout<<"输入数字: "

     cin>>p1->num

     p2=head=p1

     while(p1->num!=0)

     {

           p1 = new Node

           cout<<"输入数字: "

           cin>>p1->num

           p2->next = p1

           p2=p1

    }

     p2->next=NULL

     return head

}

void display(Node *head)

{

      Node *p

      int i

      for(p=head, i=1 p->next!=NULL i++,p=p->next)

      {

            cout<<"第"<<i<<"个元素是: "<<p->num<<endl

      }

}

void insert(Node  **head)

{

      int position

      cout<<"插入的位置: "

      cin>>position

      Node *p

      p = *head

      Node *NewNode= new Node

      cout<<"输入数字: "

      cin>>NewNode->num

      if(position == 0)

      {        

           NewNode->next = p

           *head = NewNode 

      }

}

int main()

{

     Node *a =create()

     display(a)

     insert(&a)

     display(a)

     return 0

}

其实最后你应该加个释放函数,用delete释放所有节点

InsertList(p,p1)//在第一个节点之前插入有问题啊啊啊啊啊啊

// 首先,你在外面已经分配了p1的空间,那么在里面没必要重新分配

// 其次,InsertList改变了链表的头节点位置,这里要改成p=InsertList(p,p1)

// 或者OutputList(p)改为OutputList(head)

// 再次(这一点是很重要的),每次malloc分配的空间都要你自己用free来释放

#define typename int

typedef struct node{

typename data

node * next

} node

void insert(node *list, int pos,typename x)

{

node * p

node * q

p = list

int i

for (i =1i <posi++ )

{

p = p ->next

}

q = (node*)malloc(sizeof(node))

q->data = x

q->next = p->next

p ->next = q

}

//只是随便的试了一下算法,在主函数中必须添加上stdlib.h。并且有可能还要调试。

//建议楼主可以在使用链表的时候画图,然后,思路就清晰了很多。

if any question ,call me back!!!


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11719117.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存