马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
ElemType a[100];
typedef struct Lnode //创建单链表结构体//
{
ElemType data;
struct Lnode* next;
}LinkNode;
int InsertElem(LinkNode *L, int n, ElemType e)
{
LinkNode* p, * pre, * s;
int i;
s = (LinkNode*)malloc(sizeof(LinkNode));
//s->data = e;
s->next = NULL;//插入尾部??
s->data = e;
p = L->next;
pre = L;
for (i = 0; i < n; i++) {
if (p != NULL) {
if (p->data < s->data) {
pre = p;
p = p->next;
}
else {
s->next = p;
pre->next = s;
break;
}
}
}
return ++n;
}
int main()
{
LinkNode * L, * p, * q;
ElemType i, n;
ElemType e;//待插入值
//L = (LinkNode*)malloc(sizeof(LinkNode)); //不要头结点了,直接指针指给q的头
/*p = L->next;//L的next没有被赋值就给P???
printf("请输入单链表元素的个数:");*/
scanf("%d", &n);
printf("请输入元素的值:");
for (i = 0; i < n; i++) {
scanf("%d",&a[i]);
//scanf("%d", p->data);
//p = p->next;
}
p= (LinkNode*)malloc(sizeof(LinkNode));
for (i = 0; i < n; i++) {
if ((q = (LinkNode*)malloc(sizeof(LinkNode))) != NULL)
{
q->data = a[i];
q->next = NULL;
if (i==0) L = q;//不要头结点了,直接指针指给q的头
else p->next = q;
p = q;
}
else {
printf("malloc failure");
break;
}
}
//p = NULL;
printf("请输入待插入的值:");
scanf("%d", &e);
//q = L->next;
n = InsertElem(L, n, e);
printf("输出插入后的单链表:");
for (i = 0; i < n; i++) {
printf("%2d", q->data);
q = q->next;
}
return 0;
}
|