#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node{
int data;
struct Node *next;
};
//创建带有头结点的单向链表
struct Node * SList_Creat() {
int data=0;
//创建头结点
struct Node *head=NULL,*pm=NULL,*pCur=NULL;
head = (struct Node*)malloc(sizeof(struct Node));
if (head == NULL) {
return NULL;
}
head->data = 0;
head->next = NULL;
//从键盘输入数据,创建业务结点
printf("please enter the data of node(-1:quit)");
scanf("%d", &data);
//循环创建
pCur = head;
while (data != -1) {
pm= (struct Node*)malloc(sizeof(struct Node));
if (pm == NULL) {
return NULL;
}
pm->data = data;
pm->next = NULL;
pCur->next = pm;
pCur = pCur->next;
printf("please enter the data of node(-1:quit)");
scanf("%d", &data);
}
return head;
}
//打印链表
int SLlist_Print(struct Node *head) {
if (head == NULL) {
return -1;
}
struct Node *pm = NULL;
pm = head->next;
printf("\nBegin ");
while (pm != NULL) {
printf("%d ", pm->data);
pm = pm->next;
}
printf("End\n");
}
//在值为x的节点前,插入值为y的值,若值为x的节点不存在,则插在表尾
int SLlist_NodeInsert(struct Node *head, int x, int y) {
int i = 1;
if (head == NULL) {
return -1;
}
struct Node *p1 = NULL,*p2=NULL, *tmp = NULL;
tmp = (struct Node*)malloc(sizeof(struct Node));
if (tmp == NULL) {
return -1;
}
tmp->data = y;
tmp->next = NULL;
p1 = head;
p2 = head->next;
while (p2) {
if (p2->data == x) {
break;
}
p1 = p1->next;
p2 = p2->next;
}
tmp->next = p2;
p1->next = tmp;
return 0;
}
//删除值为x的结点
int SLlist_NodeDel(struct Node *head, int x) {
if (head == NULL) {
return -1;
}
struct Node*p1 = NULL, *p2 = NULL;
p1 = head;
p2 = head->next;
while (p2) {
if (p2->data == x) {
break;
}
p1 = p2;
p2 = p2->next;
}
if (p2 == NULL) {
printf("没有找到要删除的节点\n");
return 0;
}
p1->next = p2->next;
free(p2);
return 0;
}
//销毁链表
int SLlist_Destory(struct Node*head) {
if (head == NULL) {
return -1;
}
struct Node *p = head,*tmp=NULL;
while (p) {
tmp = p->next;
free(p);
p = tmp;
}
}
//链表逆置
int SList_Resve(struct Node *head) {
if (head == NULL) {
return -1;
}
struct Node *p=NULL, *q=NULL, *t=NULL;
if (head->next == NULL || head->next->next == NULL) {
return -2;
}
p = head->next;
q = p->next;
while (q != NULL) {
//逆置之前把q的后继节点保存
t = q->next;
//逆置操作
q->next = p;
//前驱节点后移
p = q;
//逆置结点后移
q = t;
}
head->next->next = NULL;
head->next = p;
return 0;
}
void main() {
struct Node *head = NULL;
head = SList_Creat();
SLlist_Print(head);
SLlist_NodeInsert(head, 20, 19);
SLlist_Print(head);
SLlist_NodeDel(head, 20);
SLlist_Print(head);
SList_Resve(head);
SLlist_Print(head);
//SLlist_Destory(head);
system("pause");
}
链表基础(C语言实现)
最新推荐文章于 2023-08-15 16:50:52 发布