#include <stdio.h>
#include <malloc.h>
#define DATATYPE2 char
#define MAXSIZE 100
typedef struct node {
DATATYPE2 data;
struct node *next;
} LINKLIST;
//output
void output_head(LINKLIST *head) {
LINKLIST *p;
for (p = head->next; p != NULL; p = p->next) {
printf(" %c", p->data);
}
printf("\n");
}
//use toucharufa built single list with head node
LINKLIST *creatlink_head_head(LINKLIST *head) {
LINKLIST *t;
char ch;
t = (LINKLIST*) malloc(sizeof (LINKLIST));
head = t;
t->next = NULL;
printf("single,lianxu,end with $:");
while ((ch = getchar()) != '$') {
t = (LINKLIST*) malloc(sizeof (LINKLIST));
t->data = ch;
t->next = head->next;
head->next = t;
}
return (head);
}
//sort
LINKLIST sort(LINKLIST *sl) {
LINKLIST *p, *q;
int temp;
for (p = sl; p != NULL; p = p->next) {
for (q = p->next; q != NULL; q = q->next) {
if (p->data > q->data) {
temp = q->data;
q->data = p->data;
p->data = temp;
}
}
}
return (*sl);
}
//insert
LINKLIST *insert(LINKLIST *head) {
int c = 0;
char n;
printf("Enter the element that you want to insert:");
scanf("%c", &n);
LINKLIST*p;
p = (LINKLIST*) malloc(sizeof (LINKLIST));
LINKLIST*t;
t = (LINKLIST*) malloc(sizeof (LINKLIST));
LINKLIST*r;
r = (LINKLIST*) malloc(sizeof (LINKLIST));
p = head->next;
t = p;
r = p;
LINKLIST*s;
s = (LINKLIST*) malloc(sizeof (LINKLIST));
while (n > t->data) {
p = p->next;
t = p->next;
c++;
}
if (c == 1) {
s->data = n;
s->next = r->next;
r->next = s;
} else {
s->data = n;
s->next = p->next;
p->next = s;
}
return (head);
}
//delete
LINKLIST *dele(LINKLIST *head) {
LINKLIST*p;
char n;
printf("plase input dele a value\n");
scanf("%c", &n);
for (p = head; p->next != NULL; p = p->next) {
if (p->next->data == n) {
p->next = p->next->next;
}
if (p->next == NULL) break;
}
return (head);
}
main() {
LINKLIST *head = NULL;
LINKLIST *p = head;
int choose;
printf("\n Build single list:\n\n");
head = creatlink_head_head(head);
fflush(stdin);
sort(head);
printf("Output single list element's value:");
output_head(head);
while (1) {
printf("Please select the operating:");
printf("1:Insert 2:Delete\nYour choose:");
scanf("%d", &choose);
fflush(stdin);
if (choose == 1) {
insert(head);
break;
} else if (choose == 2) {
dele(head);
break;
} else {
printf("Please enter the correat choose!");
}
}
printf("Output new single list element's value:");
output_head(head);
}
有序链表插入与删除——C语言
最新推荐文章于 2022-06-30 10:38:39 发布