链表的相关操作

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstdlib>
  4 
  5 using namespace std;
  6 
  7 struct node;
  8 typedef struct node *ptrtonode;
  9 typedef ptrtonode linkhead;
 10 typedef ptrtonode position;
 11 typedef int elementype;
 12 
 13 int Empty(linkhead L);
 14 int Islast(position p);
 15 void Print(linkhead L);
 16 position Find(elementype x,linkhead L);
 17 int Delete(elementype x,linkhead L);
 18 void Insert(elementype x,position p,linkhead L);
 19 
 20 struct node{
 21     elementype element;
 22     position next;
 23 };
 24 
 25 int Empty(linkhead L){
 26     return L->next==NULL;
 27 }
 28 
 29 int Islast(position p){
 30     return p->next==NULL;
 31 }
 32 
 33 void Print(linkhead L){
 34     position p=L->next;
 35     while(p->next!=NULL){
 36         printf("%d ",p->element);
 37         p=p->next;
 38     }
 39     printf("
");
 40 }
 41 
 42 position Find(elementype x,linkhead L){ //返回元素上一个位置的指针
 43     int a=1;
 44     position p=L;
 45     while(p->next!=NULL&&p->next->element!=x){
 46         p=p->next;
 47         a++;
 48     }
 49     if(p->next!=NULL){
 50         return p;
 51     }else{
 52         return NULL;
 53     }
 54 }
 55 
 56 void Insert(elementype x,position p,linkhead L){
 57     position pp;
 58     pp=(position)malloc(sizeof(struct node));
 59     pp->element=x;
 60     pp->next=p->next;
 61     p->next=pp;
 62 }
 63 
 64 int Delete(elementype x,linkhead L){ //返回0,查找失败,无此元素。返回1,删除成功。
 65     position p1,p2;
 66     p1=Find(x,L);
 67     if(p1==NULL){
 68         return 0;
 69     }
 70     p2=p1->next;
 71     p1->next=p2->next;
 72     free(p2);
 73     return 1;
 74 }
 75 
 76 int main()
 77 {
 78     int a;
 79     int f;
 80     position head;
 81     head=(position)malloc(sizeof(struct node));
 82     position last;
 83     last=(position)malloc(sizeof(struct node));
 84     head->next=last;
 85     last->next=NULL;
 86 
 87     printf("请输入要插入的元素(整型,以0结束。):
");
 88     while(scanf("%d",&a)!=EOF&&a!=0){
 89         Insert(a,head,head);
 90     }
 91     printf("元素分别为:
   ");
 92     Print(head);
 93 
 94     printf("请输入要查找的元素:");
 95     scanf("%d",&f);
 96     position p=Find(f,head);
 97     if(p->next->element==f){
 98         printf("查找成功!
");
 99     }else{
100         printf("查找失败。
");
101     }
102 
103     printf("请输入要删除的元素:");
104     scanf("%d",&f);
105     if(Delete(f,head)==1){
106         printf("已删除。
");
107     }else{
108         printf("删除失败。");
109     }
110 
111 
112 
113 
114     return 0;
115 }

原文地址:https://www.cnblogs.com/TWS-YIFEI/p/5768211.html