//建立链表时输入-1终止输入
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node *next;
}NODE;
NODE* create(void);
void output(NODE *head);
void _free(NODE *head);
int length(NODE *head);
NODE* insert(NODE *head);
int search(NODE *head);
NODE* clear(NODE *head);
int main()
{
NODE *head;
int len=0,pos=0;
//长度和位置
head = create();
//建立链表
output(head);
//输出链表
len = length(head);
printf("\nlength=%d\n", len);
//输出链表长度
head = insert(head);
//
插入节点
output(head);
//输出链表
pos=search(head);
//赋值位置
printf("\npos=%d", pos);
head = clear(head);
//删除一个节点
output(head);
len = length(head);
//在计算链表长度
printf("\nlength=%d\n", len);
//输出链表长度
_free(head);
printf("\n");
system("pause");
return 0;
}
NODE *create(void) {
NODE *head = NULL;
NODE *p;
NODE *s;
int n;
printf("Enter chain table:");
scanf_s("%d", &n);
while (n != -1) {
p = (NODE*)malloc(sizeof(NODE));
p->num = n;
if (head == NULL) {
head = p;
s = p;
}
else {
s->next = p;
s = p;
}
scanf_s("%d", &n);
}
p->next = NULL;
return head;
}
void output(NODE* head) {
NODE *p;
p = head;
do {
printf("%d|", p->num);
p = p->next;
} while (p != NULL);
}
void _free(NODE *head) {
NODE *p, *s;
p = s = head;
do {
p = p->next;
free(s);
s = p;
} while (p != NULL);
}
int length(NODE *head) {
NODE *p = head;
int len = 0;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
NODE *insert(NODE *head) {
NODE *s, *p, *q;
s = (NODE*)malloc(sizeof(NODE));
printf("\nEnter insertnum:");
scanf_s("%d", &s->num);
s->next = NULL;
p = q = head;
p = p->next;
//printf("q->num=%d", q->num);
if (s->num <= q->num) {
s->next = q;
head = s;
return head;
}
else {
while (p != NULL && s->num > p->num) {
p = p->next;
q = q->next;
}
s->next = q->next;
q->next = s;
}
return head;
}
int search(NODE *head) {
NODE *p;
int
pos = 0, searchnum=0;
p = head;
printf("\nEnter your searchnum:");
scanf("%d", &searchnum);
while (p != NULL) {
pos++;
if (searchnum == p->num)
break;
p = p->next;
}
if(p==NULL)
printf("NO found");
return pos;
}
NODE* clear(NODE *head) {
int deletenum;
NODE *p, *q;
p = head;
q=head;
p = p->next;
printf("\nEnter your deletenum:");
scanf_s("%d", &deletenum);
if (deletenum == q->num) {
head = q->next;
free(q);
return head;
}
while (p != NULL) {
if (deletenum == p->num)
{
q->next = p->next;
free(p);
break;
}
p = p->next;
q=q->next;
}
if(p=NULL)
printf("NO found");
return head;
}