Talk is cheap, show the code
#include <stdio.h>
#include <stdlib.h>
#define ERROR -404
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* InitList (void);
void add_front (Node* head,int data);
void add_back (Node* head, int data);
void PrintList (Node* head);
int Length (Node* head);
int Get (Node* head, int l); //按位查找
int Locate (Node* head, int n); //按值查找
void Insert (Node* head, int i, int x);
void Delete (Node* head, int i);
void FreeL (Node* head);
int main ()
{
Node* head= InitList();
int num =1,i,x;
scanf("%d",&num);
while (num!= -1) {
add_front(head,num);
scanf("%d",&num);
}
PrintList(head);
printf("The length is %d\n",Length(head));
scanf("%d",&i);
printf("Get: %d\n",Get(head,i));
PrintList (head);
scanf("%d",&i);
printf("Locate: %d\n",Locate(head,i));
PrintList (head);
scanf("%d %d",&i,&x);
Insert(head,i,x);
PrintList (head);
scanf("%d",&i);
Delete(head,i);
PrintList (head);
FreeL(head);
return 0;
}
Node* InitList (void)
{
Node* head = (Node*)malloc(sizeof(Node));
head ->next = NULL; // 设置哨兵节点 mark
return head;
}
// 强行尾插,要尾插建议加入尾指针
void add_back(Node* head, int data) {
Node *p,*end=head,*q;
for ( p=head; p ; p=p->next) {
end =p;
}
q =(Node*)malloc(sizeof(Node));
end->next =q;
q->data =data;
q->next= NULL;
return ;
}
void add_front(Node* head, int data) {
Node *p = (Node *)malloc(sizeof(Node));
p -> next = head -> next;
head -> next = p;
p -> data = data;
return ;
}
void PrintList (Node* head)
{
Node* p;
for (p =head->next; p; p=p->next) {
printf("%d ",p->data);
}
printf("\n");
}
int Length (Node* head)
{
Node* p;
int sum=0;
for (p=head->next; p; p=p->next) {
sum++;
}
return sum;
}
int Get (Node* head, int l) // 按位查找
{
Node* p;
int cnt=0;
for (p=head->next; p ; p=p->next) {
cnt++;
if (cnt==l) {
return p->data;
break;
}
}
return ERROR;
}
int Locate (Node* head, int n)
{
Node* p;
int cnt=0;
for (p=head->next ; p; p=p->next) {
cnt++;
if (p->data == n) {
return cnt;
}
}
return ERROR;
}
void Insert (Node* head, int i, int x) {
Node *p,*q,*r;
int cnt=0;
for (p=head->next,q=head; q; q=p,p=p->next) {
cnt++;
if (cnt==i) {
r=(Node*)malloc(sizeof(Node));
r->data =x;
r->next =p;
q->next =r;
return ;
}
}
printf("ERROR\n");
}
void Delete (Node* head, int i)
{
int cnt=0;
Node *p,*q;
for (p=head->next,q=head; p; q=p, p=p->next) {
cnt ++;
if (cnt==i) {
q->next= p->next;
free(p);
return ;
}
}
printf("ERROR\n");
}
void FreeL (Node* head)
{
Node *p,*q;
for (p=head->next, q=head; p; q=p, p=p->next) {
free(q);
}
free(q);
}