C/C++单向链表

本文详细介绍了如何在C/C++中实现单向链表的数据结构,包括链表节点定义、插入、删除、遍历等操作,通过main.cpp、SingleList.h和SingleList.cpp三个文件进行实现。
摘要由CSDN通过智能技术生成

main.cpp

#include <stdio.h>
#include "SingleList.h"

int main(int argc, int *argv[])
{
	Node *pHead = NULL;
	for (int i = 0; i < 10; i++)
	{
		Node node;
		node.id = i;
		pHead = AddNode(pHead, node);
	}

	PrintList(pHead);

	Node *tmp = FindNode(pHead, 5);
	if (NULL != tmp)
	{
		printf("\n\n%d\t\t%p\n\n", tmp->id, tmp->next);
	}

	Node node;
	node.id = 5;
	pHead = DeleteNode(pHead, node);
	PrintList(pHead);

	return 0;
}

SingleList.h

#ifndef SINGLE_LIST
#define SINGLE_LIST

typedef struct Node{
	int id;
	Node *next;
}Node;


enum ReturnStatus{
	SingleList_Success = 0,
	SingleList_Error
};

Node* FreeList();
Node* AddNode(Node *pHead, Node node);
Node* DeleteNode(Node *pHead, Node node);
Node* FindNode(Node *pHead, int id);
int ModifyNode(Node *pHead, Node node);

void PrintList(Node *pHead);

#endif

SingleList.cpp

#include <stdio.h>
#include <stdlib.h>
#include "SingleList.h"


Node* FreeList(Node *pHead)
{
	while(NULL != pHead)
	{
		Node *tmp = pHead;
		pHead = pHead->next;
		delete tmp;
	}

	return NULL;
}

Node* AddNode(Node *pHead, Node node)
{
	Node *tmp = (Node*)malloc(sizeof(Node));
	if(NULL == tmp)
	{
		return NULL;
	}

	//在链表头部插入新节点
	tmp->id = node.id;
	tmp->next = pHead;
	pHead = tmp;

	return pHead;
}

Node* DeleteNode(Node *pHead, Node node)
{
	if (NULL == pHead)
	{
		return NULL;
	}

	//删除的节点为首节点
	if(pHead->id == node.id)
	{
		delete pHead;
		pHead = NULL;
	}
	else
	{
#if 0
		Node *pre = pHead;
		Node *cur = pHead->next;
		while(NULL != cur)
		{
			if (cur->id == node.id)
			{
				pre->next = cur->next;
				delete cur;
				return pHead;
			}
			else
			{
				pre = cur;
				cur = cur->next;
			}
		}
#else
		Node *pre = pHead;
		for (Node *cur = pHead->next; NULL != cur; pre = cur,cur = cur->next)
		{
			if (cur->id == node.id)
			{
				pre->next = cur->next;
				delete cur;
				return pHead;
			}
		}
#endif
	}

	return pHead;
}

Node* FindNode(Node *pHead, int id)
{
	for (Node *tmp = pHead; NULL != tmp; tmp = tmp->next)
	{
		if(tmp->id == id)
		{
			return tmp;
		}
	}

	return NULL;
}

int ModifyNode(Node *pHead, Node node)
{
	Node *dest = FindNode(pHead, node.id);
	if(NULL != dest)
	{
		//更新节点内容
		return SingleList_Success;
	}

	return SingleList_Error;
}


void PrintList(Node *pHead)
{
	for (Node *tmp = pHead; NULL != tmp; tmp = tmp->next)
	{
		printf("%d\t\t%p\n", tmp->id, tmp->next);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值