###### 吠错了树
2018-12-05 12:51 阅读 937

# 单链表的插入，删除，基本问题！着急！！！

#include
#include
#define INIT_SIZE 50
#define INCREM 10
#define OK 1
#define ERROR 0
typedef struct Node{
int data;
struct Node next;
}Node,*List;//
List InitList();
List CreateList();
void FreeList(List);
List InsertList(List, int, int);
List DeleteList(List, int);
List InitList()//
{
List H = (Node
)malloc(sizeof(Node));
if (H == NULL) printf("申请空间失败！");
H->next = NULL;
return H;
}
List CreateList()
{
int x;
List H = (Node*)malloc(sizeof(Node));
H->next = NULL;//
while (scanf_s("%d", &x)!=EOF)
{
List p = (Node*)malloc(sizeof(Node))；
p->data = x;
p->next = H->next;
H->next = p;
}
return H;
}
List InsertList(List H, int i, int e)
{
List q = H; int k=0;
for (k = 1; k < i; k++)//找到i的前驱结点
q = q->next;
if (q == NULL) return ERROR;
List y = (Node*)malloc(sizeof(Node));//给要新插入的结点分配内存
y->data = e;//给要新插入的结点赋值为e
y->next = q->next;
q->next = y;
return H;
}
List DeleteList(List H,int i)//删除单链表中第i位置的元素
{
int k; List q = H; //定义p为要查找的结点
for (k = 1; k i; k++)
q = q->next;
if (q == NULL) return ERROR;
List p = q->next;
q->next = p->next;
free(p);
return H;
}
void FreeList(List H)//销毁单链表
{
List p = H;
while (p)
{
p = p->next;
free(p);
p = H;
}
}
int main()
{
List p,q;
int i,e;
printf("请输入单链表中的数据：\n");
q = InitList();
q=CreateList();
for (p=q->next; p!=NULL; p=p->next)
printf("%d", q->data);
printf("\n");
printf("在第二个位置处插入元素10：\n");
InsertList(q, 2, 10);
for (p = q->next; p != NULL; p = p->next)
printf("%d", q->data);
printf("\n");
DeleteList(q, 2);
printf("删除第二个位置元素后的单链表p：\n");
for (p = q->next; p != NULL; p = p->next)
printf("%d", q->data);
printf("\n");
return 0;
}

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享