怎么写该线性表
A 0 1 2 3 4 5 6 7data 6050 78 9034 40
next3 5 7 2 0 4 1 linear_table = {
0: {'data': 60, 'next': 3},
1: {'data': 50, 'next': 5},
2: {'data': 78, 'next': 7},
3: {'data': 90, 'next': 2},
4: {'data': 34, 'next': 0},
5: {'data': None, 'next': 4},
6: {'data': 40, 'next': None},
7: {'data': None, 'next': 1}
}
参考:
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct LinkedList {
Node *head;// 头结点
} LinkedList;
// 初始化链表
LinkedList* init() {
// 申请头结点空间
Node* head = (Node*)malloc(sizeof(Node));
head->next = head;// 头结点的next指向自己,构成循环链表
LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList));
list->head = head;
return list;
}
// 插入节点
void insert(LinkedList* list, int pos, int data) {
// 找到pos的前一个节点
Node* pre = list->head;
for (int i = 1; i <= pos - 1; i++) {
pre = pre->next;
}
// 申请新节点空间
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
// 将新节点next指向pos节点
node->next = pre->next;
pre->next = node;
}
// 打印链表
void print(LinkedList* list) {
Node* cur = list->head->next;
while (cur != list->head) {
printf("%d ", cur->data);
cur = cur->next;
}
}
页:
[1]