?单链表的最后一个节点的next部分指向的是头节点
目录
typedef struct {
?? ?int data;
?? ?struct Node* next;
}Node;
Node* initList(){
?? ?Node* L = (Node*)malloc(sizeof(Node));
?? ?L->data = 0;//头结点的data表示除头结点外的结点个数
?? ?L->next = L;//此时next指向头结点自身
?? ?return L;
}
void headInsert(Node* L, int data) {
?? ?Node* node = (Node*)malloc(sizeof(Node));
?? ?node->data = data;
?? ?node->next = L->next;
?? ?L->next = node;
?? ?L->data++;
}
void tailInsert(Node* L, int data) {
?? ?Node* node = (Node*)malloc(sizeof(Node*));
?? ?Node* n = L;
?? ?node->data = data;
?? ?while (n->next != L) {
?? ??? ?n = n->next;
?? ?}
?? ?n->next = node;
?? ?node->next = L;
?? ?L->data++;
}
int delete(Node* L, int data) {
?? ?Node* prenode = L;
?? ?Node* node = L->next;
?? ?while (node != L) {
?? ??? ?if (node->data == data){
?? ??? ??? ?prenode->next = node->next;
?? ??? ??? ?L->data--;
?? ??? ??? ?free(node);
?? ??? ??? ?return 1;
?? ??? ??? ?}
?? ??? ?prenode = node;
?? ??? ?node = node->next;
?? ?}
?? ?return 0;
}
void printList(Node* L) {
?? ?Node* node = (Node*)malloc(sizeof(Node));
?? ?node = L->next;
?? ?while (node != L) {
?? ??? ?printf("%d->", node->data);
?? ??? ?node = node->next;
?? ?}
?? ?printf("以上%d个数循环\n",L->data );
}
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int data;
struct Node* next;
}Node;
//初始化一个含头结点的链表
Node* initList(){
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;//头结点的data表示除头结点外的结点个数
L->next = L;//此时next指向头结点自身
return L;
}
void headInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = L->next;
L->next = node;
L->data++;
}
void tailInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node*));
Node* n = L;
node->data = data;
while (n->next != L) {
n = n->next;
}
n->next = node;
node->next = L;
L->data++;
}
int delete(Node* L, int data) {
Node* prenode = L;
Node* node = L->next;
while (node != L) {
if (node->data == data){
prenode->next = node->next;
L->data--;
free(node);
return 1;
}
prenode = node;
node = node->next;
}
return 0;
}
void printList(Node* L) {
Node* node = (Node*)malloc(sizeof(Node));
node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("以上%d个数循环\n",L->data );
}
int main() {
Node* L = initList();
headInsert(L, 1);
headInsert(L, 2);
headInsert(L, 3);
headInsert(L, 4);
headInsert(L, 5);
tailInsert(L, 6);
tailInsert(L, 7);
printList(L);
delete(L, 8);
printList(L);
delete(L, 5);
printList(L);
return 0;
}
?
?