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
| #include <iostream>
using namespace std;
typedef struct Node { int data; struct Node *next; }Node;
typedef struct Node *LinkList;
void initLinkList(LinkList *L) { (*L) = new Node; (*L)->data = 0; (*L)->next = NULL; }
bool insertLinkList(LinkList head, int pos, int value) { LinkList p = head, t; int j = 1;
while (p && j < pos) { p = p->next; j++; }
if (!(p) || j > pos) return false;
t = new Node; t->data = value; t->next = p->next; p->next = t; head->data++;
return true; }
bool deleteLinkList(LinkList l, int pos, int *value) { LinkList p = l, q; int j = 1;
while (p->next && j < pos) { p = p->next; j++; }
if (!(p->next) || j > pos) return false;
q = p->next; p->next = q->next; delete(q); l->data--; return true; }
void clearLinkList(LinkList l) { LinkList p = l->next, q; l->next = NULL; while (p) { q = p->next; delete (p); p = q; l->data--; } }
void showLinkList(LinkList l) { cout << "Length is " << l->data << endl; l = l->next; while (l) { cout << l->data << "\t"; l = l->next; } cout << endl;
return ; }
int main() { LinkList head = NULL; initLinkList(&head);
int value_del; deleteLinkList(head, 1, &value_del); for (int i = 1; i <= 10; i++) { insertLinkList(head, i, i); } insertLinkList(head, 4, 10); showLinkList(head);
deleteLinkList(head, 4, &value_del); showLinkList(head);
clearLinkList(head); showLinkList(head);
return 0; }
|