1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| #include<iostream> #include<string>
using namespace std;
typedef int ElemType; typedef int Status;
typedef struct LNode { ElemType data; struct LNode* next; }LNode,*LinkList;
Status InitList(LinkList &L) { L = new LNode; L->next = NULL; return 1; }
Status GetElem(LinkList L,int i,ElemType &e) { LNode *p = L->next; int j = 1; while (p && j<i) { p = p->next; j++; } if (!p || j > i) { return 0; } e = p->data; return p->data; }
LNode* LocateElem(LinkList L, ElemType e) { LNode* p = L->next; while (p && p->data!=e) { p = p->next; } return p; }
Status ListInsert(LinkList& L, int i, ElemType e) { if (i<1) { return 0; } LNode* p = L; int j = 0; while (p && (j<i-1)) { p = p->next; j++; } if (!p || j>i-1) { return 0; } LNode* s = new LNode; s->data = e; s->next = p->next; p->next = s;
return 1; }
Status ListDelete(LinkList& L, int i) { LNode* p = L; int j = 0; while (p->next&&(j<i-1)) { p = p->next; j++; } if (!(p->next)||(j>i-1)) { return 0; } LNode* q = p->next; p->next = q->next; delete q;
return 1; }
int main() { LinkList L; InitList(L); for (int i = 1; i < 6; i++) { ListInsert(L, 1, i); } int e; for (int i = 1; i <= 5; i++) { cout << GetElem(L, i, e) << endl; } cout << "5的地址为:" << LocateElem(L, 5) << endl; ListDelete(L, 1); cout << "删除第一个元素5:" << endl; for (int i = 1; i < 5; i++) { cout << GetElem(L, i, e) << endl; } return 1; }
|