单链表的操作

    技术2022-07-10  121

    单链表的操作:

    单链表节点定义

    typedef struct LNode { int data; LNode* next; }LNode;

    尾插法建立单链表

    void CreateListR(LNode*& C, int a[], int n) //尾插法建立链表 { C = (LNode*)malloc(sizeof(LNode)); C->next = NULL; LNode* s; LNode* r; r = C; for (int i = 0; i < n; i++) { s = (LNode*)malloc(sizeof(LNode)); s->data = a[i]; r->next = s; r = r->next; } r->next = NULL; }

    头插法建立单链表

    void CreateListR(LNode*& C, int a[], int n) //头插法建立链表 { C = (LNode*)malloc(sizeof(LNode)); C->next = NULL; LNode* s; for (int i = 0; i < n; i++) { s = (LNode*)malloc(sizeof(LNode)); s->data = a[i]; s->next = C->next; C->next = s; } }*

    插入元素

    void InsertList(LNode* &C, int i, int e) //在第i个位置之前插入元素e,i从1开始 { LNode* p = C; int j = 0; while (p && j < i - 1) { p = p->next; ++j; } if (!p || j > i - 1)return; LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = e; s->next = p->next; p->next = s; return; }

    删除元素

    void DeleteList(LNode*& C, int i, int &k)//删除第i个节点,并用k返回其值 { LNode* p = C; int j = 0; while (p->next && j < i - 1) { p = p->next; ++j; } if (!p->next || j > i - 1)return; LNode* q; q = p->next; p->next = q->next; k = q->data; free(q); return; }

    完整代码如下:

    #include<iostream> using namespace std; typedef struct LNode { int data; LNode* next; }LNode; void CreateListR(LNode*& C, int a[], int n) //尾插法建立链表 { C = (LNode*)malloc(sizeof(LNode)); C->next = NULL; LNode* s; LNode* r; r = C; for (int i = 0; i < n; i++) { s = (LNode*)malloc(sizeof(LNode)); s->data = a[i]; r->next = s; r = r->next; } r->next = NULL; } /*void CreateListR(LNode*& C, int a[], int n) //头插法建立链表 { C = (LNode*)malloc(sizeof(LNode)); C->next = NULL; LNode* s; for (int i = 0; i < n; i++) { s = (LNode*)malloc(sizeof(LNode)); s->data = a[i]; s->next = C->next; C->next = s; } }*/ void InsertList(LNode* &C, int i, int e) //在第i个位置之前插入元素e,i从1开始 { LNode* p = C; int j = 0; while (p && j < i - 1) { p = p->next; ++j; } if (!p || j > i - 1)return; LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = e; s->next = p->next; p->next = s; return; } void DeleteList(LNode*& C, int i, int &k)//删除第i个节点,并用k返回其值 { LNode* p = C; int j = 0; while (p->next && j < i - 1) { p = p->next; ++j; } if (!p->next || j > i - 1)return; LNode* q; q = p->next; p->next = q->next; k = q->data; free(q); return; } void ShowList(LNode* C) { while (C->next) { cout << C->next->data << " "; C = C->next; } cout << endl; } int main() { LNode* C = (LNode*)malloc(sizeof(LNode)); int R[] = { 1,2,3,4,6,7 }; CreateListR(C, R, 6); ShowList(C); cout << "插入5之后" << endl; InsertList(C, 5, 5); ShowList(C); cout << "删除7之后" << endl; int k = 0; DeleteList(C, 7, k); ShowList(C); cout << "删除的元素为:" << k << endl; system("pause"); return 0; }

    运行结果

    Processed: 0.026, SQL: 9