/*
* main.c
* 链表
* Created on: Oct 29, 2010
* Author: jenson
*/
#include <stdio.h>
#include <stdlib.h>
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;
}
}
}