单链表的操作

来源:互联网 发布:软件技术支持面试题 编辑:程序博客网 时间:2024/05/17 02:30

Talk is cheap, show the code


#include <stdio.h>#include <stdlib.h>#define ERROR -404typedef struct Node {int data;struct Node* next;} Node;Node* InitList (void);void add (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(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; // 设置哨兵节点 return head;}void add(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;}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(p);}


0 0
原创粉丝点击