//动态链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int data; //数据域
struct Node *next; //指针域
}Node;
typedef Node *pNode;
//创建头节点
//链表的头结点地址由函数返回
Node *SListCreate()
{
//头结点不存储有效数据,仅作为标志
pNode head = NULL;
head = (pNode)malloc(sizeof(Node));
if (head == NULL) {
return NULL;
}
//给head的成员变量赋值
head->data = 0;
head->next = NULL;
pNode current = head;
pNode pNew = NULL;
int input;
while (1) {
printf("input some data :\n");
scanf("%d", &input);
if (input == -1) {
break;
}
pNew = (pNode)malloc(sizeof(Node));
if (pNew == NULL) {
continue;
}
//pNew成员变量赋值
pNew->data = input;
pNew->next = NULL;
//建立链表关系:
//当前结点的next指向pNew
current->next = pNew;
//pNew下一个结点指向NULL
pNew->next = NULL;
//把current移动到pNew
current = pNew;
}
return head;
}
//链表的遍历
int SListPrint(pNode head)
{
if (head == NULL) {
return -1;
}
//取出第一个有效结点(头结点的next)
pNode current = head->next;
printf("head -> ");
while (current != NULL) {
printf("data: %d; ", current->data);
//移动当前结点
current = current->next;
}
printf(" NULL\n");
return 0;
}
//增加结点,数据域为x的结点前插入y,没有则放到最后
int SListNodeInsert(pNode head, int x, int y)
{
if (head == NULL) {
return -1;
}
pNode pPre = head;
pNode pCurr = head->next;
while (pCurr != NULL) {
if (pCurr->data == x) //找到了匹配的结点
break;
//pPre指向pCur位置
pPre = pCurr;
pCurr = pCurr->next;
}
//2种情况
//1.找到匹配的结点,pCurr为匹配的结点,pPre为上一个
//2.没有找到匹配的结点,pCurr为空结点,pPre为最后一个
//给pNew动态分配空间
pNode pNew = (pNode)malloc(sizeof(Node));
if (pNew == NULL) {
return -2;
}
//给pNew的成员变量赋值
pNew->data = y;
pNew->next = NULL;
//插入指定位置
pPre->next = pNew;
pNew->next = pCurr;
return 0;
}
//删除第一个值为x的结点,有重复的暂不考虑
int SListNodeDelete(pNode head, int x)
{
if (head == NULL) {
return -1;
}
pNode pPre = head;
pNode pCurr = head->next;
int flag = 0; //0没找到, 1找到
while (pCurr != NULL) {
if (pCurr->data == x) {//找到了匹配的结点
pPre->next = pCurr->next;
free(pCurr);
pCurr = NULL;
flag = 1;
break;
}
//pPre指向pCur位置
pPre = pCurr;
pCurr = pCurr->next;
}
if ( flag == 0) {
printf("the node no found !\n");
return;
}
return 0;
}
//清空申请的内存空间
int SListNodeDestory(pNode head)
{
if (head == NULL) {
return -1;
}
pNode tmp = NULL;
int i = 0;
while (head != NULL) {
tmp = head->next;
free(head);
head = tmp;
i++;
}
printf("free %d times\n", i);
return 0;
}
int main(void)
{
pNode head = NULL;
head = SListCreate();
SListPrint(head);
//插入节点
printf("insert x before y\n");
int x, y;
printf("x :");scanf("%d", &x);
printf("y :");scanf("%d", &y);
SListNodeInsert(head, x, y);
SListPrint(head);
//删除结点
printf("delete a node :");
int w;
scanf("%d", &w);
SListNodeDelete(head, w);
printf("delete result :\n");
SListPrint(head);
//释放空间
SListNodeDestory(head);
printf("is end\n");
return 0;
}
记录·看视频学习:动态链表的操作(创建,插入,释放)。