c语言链表代码大全,C语言实现链表
/*
* main.c
*? 鏈表
*? Created on: Oct 29, 2010
*????? Author: jenson
*/
#include
#include
struct chain {
int value;
struct chain *next;
};
struct chain *create();
struct chain * insert(struct chain *head, int a, int b);
struct chain * delete(struct chain *head, int a);
void display(struct chain * head);
int main() {
struct chain *q, *head;
int a, b;
q = create();
head = q;
display(q);
printf("\n請輸入的表元素數據位于哪個數據之前:");
scanf("%d", &a);
printf("\n請輸入所要插入的數據:");
scanf("%d", &b);
q = insert(head, a, b);
display(q);
printf("\n請輸入所要刪除的數據:");
scanf("%d", &b);
head = q;
q = delete(head, b);
display(q);
free(q);
return 0;
}
struct chain * create() {
struct chain * head, *tail, *p;
int x;
head = tail = NULL;
int i = 0;
for (i = 0; i < 4; i++) {
printf("insert data %d:", i);
scanf("%d", &x);
p = (struct chain *) malloc(sizeof(struct chain));
if (p == NULL) {
perror("malloc");
exit(1);
}
p->value = x;
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail = tail->next = p;
}
}
return head;
}
struct chain * insert(struct chain *head, int a, int b) {
struct chain *p, *q, *s;
s = (struct chain *) malloc(sizeof(struct chain));
if (s == NULL) {
perror("insert create");
exit(1);
}
s->value = b;
if (head == NULL) {
head = s;
s->next = head;
}
if (head->value == a) {
s->next = head;
head = s;
} else {
p = head;
while ((p->value != a) && (p->next != NULL)) {
q = p;
p = p->next;
}
if (p->value == a) {
q->next = s;
s->next = p;
} else {//插入節點s作為表尾
p->next = s;
s->next = NULL;
}
}
return head;
}
struct chain * delete(struct chain *head, int a) {
struct chain *p, *q;
if (head == NULL) {
perror("空鏈表,退出\n");
exit(1);
} else if (head->value == a) {//第一個節點為a節點
p = head;
head = p->next;
} else {
p = head;
while (p->value != a && p->next != NULL) {
q = p;
p = p->next;
}
if (p->value != a) {
printf("沒有找到節點%d\n", a);
} else {
q->next = p->next;
free(p);
}
}
return head;
}
void display(struct chain * head) {
if (head != NULL) {
struct chain * p;
p = head;
while (p != NULL) {
printf("%d\t", p->value);
p = p->next;
}
}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的c语言链表代码大全,C语言实现链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: d800e和d800的区别
- 下一篇: c语言char类型溢出,C语言中数据溢出