zoukankan      html  css  js  c++  java
  • 数据结构-单链表

     
    1
    #include <iostream> 2 #include <stdlib.h> 3 using namespace std; 4 //单链表 5 typedef struct LNode 6 { 7 int data; 8 struct LNode *next; 9 }LNode; 10 11 void CreateHead(LNode *&L,int a[],int n) 12 {//头插法建链表 13 LNode *p; 14 int i; 15 L=(LNode*)malloc(sizeof(LNode)); 16 L->next=NULL; 17 for(i=0;i<n;++i) 18 { 19 p=(LNode*)malloc(sizeof(LNode)); 20 p->data=a[i]; 21 p->next=L->next; 22 L->next=p; 23 } 24 } 25 26 void CreateRear(LNode *&L,int a[],int n) 27 {//尾插法建链表 28 LNode *p,*r; 29 int i; 30 L=(LNode*)malloc(sizeof(LNode)); 31 L->next=NULL; 32 r=L; 33 for(i=0;i<n;++i) 34 { 35 p=(LNode*)malloc(sizeof(LNode)); 36 p->data=a[i]; 37 r->next=p; 38 r=r->next; 39 } 40 r->next=NULL; 41 } 42 43 int Delete(LNode *&L,int e) 44 {//存在,删除的元素值为e并返回1,否则,返回0 45 LNode *p,*q; 46 p=L; 47 while(p->next!=NULL) 48 { 49 if(p->next->data==e) 50 break; 51 p=p->next; 52 } 53 if(p->next==NULL) 54 return 0; 55 else 56 { 57 q=p->next; 58 p->next=p->next->next; 59 free(q); 60 } 61 return 0; 62 } 63 64 int LocateElem(LNode *L,int e) 65 { 66 LNode *p; 67 int loc=0; 68 p=L->next; 69 while(p!=NULL) 70 { 71 ++loc; 72 if(p->data==e) 73 { 74 return loc; 75 } 76 p=p->next; 77 } 78 return 0; 79 } 80 81 void Print(LNode *L) 82 { 83 LNode *p; 84 p=L->next; 85 while(p) 86 { 87 cout<<" "<<p->data<<" "; 88 p=p->next; 89 } 90 } 91 92 int main() 93 { 94 LNode *L; 95 int a[10]={1,2,3,4,5,6,7,8,9,10},n=10; 96 int e=5,x=3,loc; 97 cout<<"待建表的元素序列为: "; 98 for(int i=0;i<n;++i) 99 cout<<" "<<a[i]<<" "; 100 101 cout<<" -------------------------------------"<<endl; 102 cout<<"采用头插法建链表: "; 103 CreateHead(L,a,n); 104 Print(L); 105 106 cout<<" -------------------------------------"<<endl; 107 cout<<"采用尾插法建链表: "; 108 CreateRear(L,a,n); 109 Print(L); 110 111 cout<<" -------------------------------------"<<endl; 112 cout<<"删除元素5后: "; 113 Delete(L,e); 114 Print(L); 115 116 cout<<" -------------------------------------"<<endl; 117 cout<<"查找元素3的位置:"; 118 if((loc=LocateElem(L,x))==0) 119 cout<<"元素"<<x<<"不在链表中"<<endl; 120 else 121 cout<<loc<<endl; 122 123 return 0; 124 }
    
    
  • 相关阅读:
    hdu 2019 数列有序!
    hdu 2023 求平均成绩
    HDU 5805 NanoApe Loves Sequence (思维题) BestCoder Round #86 1002
    51nod 1264 线段相交
    Gym 100801A Alex Origami Squares (求正方形边长)
    HDU 5512 Pagodas (gcd)
    HDU 5510 Bazinga (字符串匹配)
    UVALive 7269 Snake Carpet (构造)
    UVALive 7270 Osu! Master (阅读理解题)
    UVALive 7267 Mysterious Antiques in Sackler Museum (判断长方形)
  • 原文地址:https://www.cnblogs.com/Xbert/p/5085337.html
Copyright © 2011-2022 走看看