0


多快好省地写一个单链表(单链表的增删查改)包括测试 每个结点只存来一个整型和下一个结点的地址

SList.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
//结点
typedef int SListDataType;
 typedef struct SListNode
{
	SListDataType data;
	struct SListNode* next;

}SListNode;
 SListNode* BuySListNode(SListDataType x);
 void SListPushBack(SListNode** pphead, SListDataType x);
 void SListPopBack(SListNode** pphead);
 void SListPushFront(SListNode** pphead, SListDataType x);
 void SListPopFront(SListNode** pphead);
 SListNode* SListFind(SListNode** pphead, SListDataType x);
 void SListPrint(SListNode* phead);

SList.c
#include"SList.h"
//链表的遍历
SListNode* BuySListNode(SListDataType x)
{
	SListNode* newNode = (SListNode*)malloc(sizeof(SListNode));
	if (newNode == NULL)
	{
		printf("申请结点失败\n");
		exit(-1);
	}
	newNode->data = x;
	newNode->next = NULL;
	return newNode;
}
void SListPrint(SListNode* phead)
{
	SListNode* cur = phead;
	while (cur != NULL)
	{
		printf("%d", cur->data); 
			cur = cur->next;
			   
	}
}
void SListPushBack(SListNode** pphead, SListDataType x)
{

	SListNode* newNode = BuySListNode(x);
	if (*pphead == NULL)
	{
		*pphead = newNode;

    }
	else {
        //找到尾tail
		SListNode* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		//插入结点
		tail->next = newNode;

	}
	 }
void SListPopBack(SListNode**pphead)
{
	//1、空
	if (*pphead == NULL)
	{
		return;
	}
	//2.一个
	else if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
		
	}
	//3.一个以上
	else
	{   //找尾,并保留尾的上一个
		SListNode* prev = NULL;
		SListNode* tail = *pphead;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		prev->next=NULL;
    }
}
void SListPushFront(SListNode** pphead, SListDataType x)
{
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SListPopFront(SListNode** pphead)
{
	//1.为空则不删
	if (*pphead == NULL)//防止出现空指针被解应用的情况
	{
		return;
	}
	//2.如果有一个节点+//3.如果有一个以上节点
	else
	{
		SListNode* next = (*pphead)->next;//先保存下一个节点的地址,再free释放
		free(*pphead);
		*pphead = next;
	}
}//注意链表中查就可以用来改
//单链表查找
SListNode* SListFind(SListNode**pphead, SListDataType x)
{
	SListNode* cur =*pphead;
	while (cur)//空指针其实就是0
	{
		if (cur->data == x)
		{
			return cur;

		}

	}return NULL;

}

test.c
#include "SList.h"
int main()
{
	 SListNode* pList = NULL;
	 SListPushBack(&pList, 2);
	 SListPushBack(&pList, 2);
	 SListPushBack(&pList, 2);
	 SListPushBack(&pList, 7);
	 SListPushBack(&pList, 7);
	 SListPopBack(&pList);
	 SListPushFront(&pList, 3);
	 SListPopFront(&pList);
	 SListNode*pos=SListFind(&pList, 7);
	 if (pos)//不为空
	 {
		 pos->data = 30;
	 }
	 SListPrint(pList);
	return 0;
}
标签: 链表 数据结构 c++

本文转载自: https://blog.csdn.net/qq_30677815/article/details/123411316
版权归原作者 小赵同学121 所有, 如有侵权,请联系我们删除。

“多快好省地写一个单链表(单链表的增删查改)包括测试 每个结点只存来一个整型和下一个结点的地址”的评论:

还没有评论