结点
typedef struct LNode { int data; struct LNode* next; }LNode, *LinkList;
输出
void Print(LinkList L) { LinkList p = L->next; while (p != NULL) { cout << p->data << " "; p = p->next; } cout << "\n"; }
链表初始化头插法
接收参数:LinkList& L, int n,代表链表头结点引用L,链表结点数为n;
bool headInitList(LinkList& L, int n) { if (n<0) return false; while (n--) { LinkList p = new LNode; cin >> p->data; LinkList tmp = L->next; // tmp保存首个结点 L->next = p; // 将p插入到头结点后 p->next = tmp; // 将tmp插入到p后 } }
链表初始化尾插法
接收参数:LinkList& L, int n,LinkList& tail 代表链表头结点引用L,链表结点数为n,链表尾结点引用tail;
bool tailInitList(LinkList& L, int n, LinkList& tail) { if (n<0) return false; tail = L; while (n--) { LinkList p = new LNode; p->next = NULL; cin >> p->data; tail->next = p; tail = p; } return true; }
插入结点
bool insertList(LinkList& L, int i, LinkList& insert) { if (i<=0) { cout << "NO1"; return false;} LinkList p = L; int j=0; while (j<i-1 && p) { j++; p = p->next; } if (j!=i-1) { cout << "NO2"; return false; } LinkList tmp = p->next; p->next = insert; insert->next = tmp; return true; }
删除结点
bool popList(LinkList& L, int i, LinkList& pop) { if (i<=0) {cout << "NO\n"; return false;} LinkList p = L; int j=0; while (j<i-1 && p->next) { j++; p = p->next; } if (j!=i-1) {cout << "NO2\n"; return false;} LinkList tmp = p->next; p->next = tmp->next; pop = tmp; return true; }
链表转置
LinkList reverseList(LinkList& L) { if (!(L->next)) { cout << "NO\n"; return false; } LinkList pre = NULL; LinkList cur = L->next; delete L; while (cur) { LinkList tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } LinkList head = new LNode; //增加一个头结点 head->next = pre; return head; }
链表合并
void unnionList(LinkList& tail_L1, LinkList& L2) { tail_L1->next = L2->next; delete L2; }