按你的要求写了个,供参考:
#include "stdio.h"
#include "stdlib.h"
struct node{
int data;
struct node *pNext;
};
/*建立n个元素的链表*/
struct node *CreatLink(int n)
{
int i;
struct node *pHead, *p,*q;
if(n<=0)return NULL;
pHead=(struct node*)malloc(sizeof(struct node));
if(NULL == pHead) return NULL;
q = pHead;
q->pNext = NULL;
printf("\n创建链表:请输入%d个整数:",n);
scanf("%d",&(q->data));
for(i=0;i{
p=(struct node*)malloc(sizeof(struct node));
if(p == NULL)
{
printf("alloc error\n");
exit(1);
}
else
{
q->pNext = p;
q=p;
q->pNext = NULL;
scanf("%d",&(q->data));
}
}
return pHead;
}
/*输出链表*/
int PrintLink(struct node *pHead)
{
struct node *p,*q;
printf("\n输出链表:");
if(NULL == pHead)
{
printf("空链表!");
return 0;
}
q = pHead;
p=q->pNext;
while(NULL != p)
{
printf("%d -> ",q->data );
q=p;
p=q->pNext;
}
printf("%d .",q->data );
return 0;
}
/*插入链表,在第 n 个位置 插入元素 Element */
int InsertLink(struct node *pHead, int n, int Element )
{
int i;
struct node *p,*q ;
if(NULL == pHead) return 0;
q = pHead;
p=q->pNext;
i=1;
printf("\n插入链表,在第 %d 个位置 插入元素 %d .",n, Element);
while(i{
q=p;
p=q->pNext;
i++;
}
if(i < n)
{
printf("\n 错误,原链表长度小于 %d !",n);
return -1;
}
else
{
p=(struct node*)malloc(sizeof(struct node));
if(p == NULL)
{
printf("alloc error\n");
exit(1);
}
else
{
p->data = Element;
p->pNext = q->pNext ;
q->pNext = p;
}
}
return 0;
}
/*单向链表演示程序
能不能提供一个c语言结构体单向链表插入节点的程序?
用户每输入一个数据链表就多一节。希望用malloc,不要用new,不要用typedef,不要附加其他功能,
现在有关的程序都看不懂……谢谢!
*/
int main()
{
struct node *head;
head = CreatLink(6);
PrintLink(head);
InsertLink(head,3,1111);
PrintLink(head);
system("pause");
return 0;
}