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

Python012

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释放所有节点。

#include

<stdio.h>

#include

<stdlib.h>

//使用结构体构建链表

struct

node{

int

data

struct

node

*next

}

void

main()

{

int

a,n=1

struct

node

*p,*head,*t

head=(struct

node

*)malloc(sizeof(struct

node))

//p=(struct

node

*)malloc(sizeof(struct

node))

//申请动态空间

p=head

//申请动态空间

t=(struct

node

*)malloc(sizeof(struct

node))

for(n<=5n++)

//输入1,3,5,7,9

{

p->data=2*n-1

p->next=(struct

node

*)malloc(sizeof(struct

node))

p=p->next

}

printf("原始链表如下:\n")

//输出原始链表

for(p=headp->next!=NULLp=p->next)

{

printf("%d

",p->data)

}

printf("\n请输入需要插入的数据\n")

//输入所要插入的新数据

scanf("%d",&a

)

for(p=headp->next!=NULL)

//按顺序插入相应位置

{

if(p->data

<=

a

&&

(p->next)->data

>=

a)

{

t->data

=a

t->next

=p->next

p->next=t

break

}

p=p->next

}

printf("插入新数据后的链表\n")

//输出插入新数据的链表

for(p=headp->next!=NULL)

{

printf("%d

",p->data)

p=p->next

}

printf("\n")

free(p)

free(head)

free(t)

}