线性表——双向链表

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
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
 
using namespace std;
 
using ElemType = int;
 
// 双向链表结点
class Node {
public:
    ElemType data;
    Node *next;
    Node *prior;
};
 
// 初始化链表
void initList(Node *head, int n)
{
    srand(time(NULL));
    Node *p = head, *r = head;
    while (n--) {
        Node *q = (Node*)malloc(sizeof(Node));
        q->data = rand()%100 - 1;
        p->next = q;
        q->prior = p;
        q->next = r;
        r->prior = q;
        p = q;
    }
}
 
// 增加某结点
void addNode(Node *head, int i, ElemType val)
{
    int j = 0;
    Node *p = head;
    while (1) {
        if (j == i - 1) {
            Node *q = (Node*)malloc(sizeof(Node));
            q->data = val;
            q->prior = p;
            q->next = p->next;
            p->next->prior = q;
            p->next = q;
            break;
        }
        j++;            // p指向第j个结点
        p = p->next;
    }
}
 
// 删除某结点
void delNode(Node *head, int i)
{
    int j = 0;
    Node *p = head;
    while (1) {
        if (j == i) {
            p->prior->next = p->next;
            p->next->prior = p->prior;
            break;
        }
        j++;
        p = p->next;
    }
}
 
// 取某结点的值
void getNode(Node *head, int i)
{
    int j = 0;
    Node *p = head;
    while (1) {
        if (j == i) {
            cout << "第" << i << "个结点的值为:" << p->data << endl;
            break;
        }
        j++;
        p = p->next;
    }  
}
 
// 打印双向链表
void print(Node *head)
{
    Node *p = head;
    p = p->next;
    while (p != head) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
}
 
 
int main()
{
    Node *head = (Node*)malloc(sizeof(Node));
    head->prior = head;
    head->next = head;
    initList(head, 5);
    print(head);
    addNode(head, 2, 100);
    print(head);
    delNode(head, 2);
    print(head);
    getNode(head, 2);
}

  

posted @   GGBeng  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)
点击右上角即可分享
微信分享提示