![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef int ElemType; 4 /** 5 * 双向链表 6 */ 7 typedef struct Node 8 { 9 struct Node *pre; 10 ElemType data; 11 struct Node *next; 12 } Node; 13 14 void InitList(Node *&L) 15 { 16 L = (Node *)malloc(sizeof(Node)); 17 L -> pre = NULL; 18 L -> next = NULL; 19 } 20 21 int GetLength(Node *L) 22 { 23 int length = 0; 24 Node *p = L -> next; 25 while(p != NULL) 26 { 27 length++; 28 p = p -> next; 29 } 30 return length; 31 } 32 33 int GetElem(Node *L, int i, ElemType &e) 34 { 35 Node *p = L -> next; 36 if(i < 1 || i > GetLength(L)) 37 return 0; 38 for(int j = 1; j < i; j++) 39 { 40 p = p -> next; 41 } 42 e = p -> data; 43 return 1; 44 } 45 46 int Lacate(Node *L, ElemType x) 47 { 48 int pos = 1; 49 Node *p = L -> next; 50 while(p != NULL && p -> data != x) 51 { 52 p = p -> next; 53 pos++; 54 } 55 if(p == NULL) 56 return 0; 57 else return pos; 58 } 59 60 int InsertElem(Node *L, ElemType x, int i) 61 { 62 63 Node *p = L, *s; 64 if(i < 1 || i > GetLength(L) + 1) 65 return 0; 66 67 for(int j = 1; j < i; j++) 68 { 69 p = p -> next; 70 } 71 s = (Node *)malloc(sizeof(Node)); 72 s -> data = x; 73 s->next=NULL; 74 s->pre =NULL; 75 76 s -> next = p -> next; 77 if(p -> next != NULL) 78 p -> next -> pre = s; 79 p -> next = s; 80 s -> pre = p; 81 return 1; 82 } 83 84 int DelElem(Node *L, int i) 85 { 86 if(i < 1 || i > GetLength(L)) 87 return 0; 88 Node *p = L, *q; 89 for(int j = 1; j < i; j++) 90 { 91 p = p -> next; 92 } 93 q = p -> next; 94 p -> next = q -> next; 95 q -> next -> pre = p; 96 free(q); 97 return 1; 98 } 99 100 void PrintList(Node *L) 101 { 102 Node *p = L -> next; 103 while(p != NULL) 104 { 105 cout << p -> data << endl; 106 p = p -> next; 107 } 108 } 109 110 void BackPrintList(Node *L) 111 { 112 Node *p = L; 113 for(int j = 1; j <= GetLength(L); j++) 114 { 115 p = p -> next; 116 } 117 while(p != NULL) 118 { 119 if(p -> pre == NULL) 120 break; 121 cout << p -> data << endl; 122 p = p -> pre; 123 } 124 } 125 126 127 int main() 128 { 129 Node *L; 130 InitList(L); 131 InsertElem(L,1,1); 132 InsertElem(L,2,1); 133 InsertElem(L,3,1); 134 InsertElem(L,4,1); 135 InsertElem(L,5,1); 136 InsertElem(L,6,1); 137 138 PrintList(L); 139 140 cout << "Reverse output elements:" << endl; 141 BackPrintList(L); 142 143 cout << "size:" << GetLength(L) << endl; 144 145 DelElem(L,1); 146 cout << "After deleting the first element :" << endl; 147 PrintList(L); 148 149 cout << "2 in the table position :" << endl; 150 cout << Lacate(L,2) << endl; 151 152 ElemType e; 153 GetElem(L,1,e);//将第一个元素的值取出 154 cout <<"The value of the first element is " << e << endl; 155 return 0; 156 }
好好的,生活还要继续,,,