参考:
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;
}
}
|