剑指offer--1.删除链表中某个节点 2.从尾到头打印链表

#include<stdio.h>
#include<assert.h>
#include<malloc.h>
struct ListNode
{
	int data;
	struct ListNode* next;
};
//创建链表
void CreatListNode(struct ListNode** phead, int data)
{
	struct ListNode* pnew=malloc(sizeof(struct ListNode));
	pnew->data=data;
	pnew->next=NULL;
	if(*phead==NULL) //空链表
		*phead=pnew; //phead是一个指向指针的指针,每次保存头节点的地址
	else
	{
		struct ListNode* cur=*phead;
		while(cur->next!=NULL)//找到最后一个节点
			cur=cur->next;
		cur->next=pnew;
	}
}
//回收链表
void Destory(struct ListNode** phead)
{
	assert(phead);
	struct ListNode* cur=*phead;
	struct ListNode* del=NULL;
	while(cur)
	{
		del=cur;
		cur=cur->next;
		free(del);
	}
}
//从头到尾打印链表
void Display(struct ListNode** phead)
{
	assert(phead);
	struct ListNode* cur=*phead;
	while(cur)
	{
		printf("%d->",cur->data);
		cur=cur->next;
	}
	printf("NULL\n");
}
//删除某个含某值的节点
void RemoveNode(struct ListNode** phead,int data)
{
	assert(phead);
	struct ListNode* cur=*phead;
	struct ListNode* prev=*phead;
	if(cur->data==data)
	{
		*phead=cur->next;
		prev->next=NULL;
		free(prev);
		return;
	}
	while(cur)
	{
		if(cur->data==data)
		{
			prev->next=cur->next;
		    free(cur);
			cur->next=NULL;
			return;
		}
		else
		{
			prev=cur;
			cur=cur->next;
		}
	}
}
//递归的思想  从尾到头打印链表
//也可以用C++写调用库里的stack
void printf_prevtoend(struct ListNode* cur)
{
	if(cur==NULL)
	{
		return;
	}
	else
		printf_prevtoend(cur->next);
	printf("%d->",cur->data);
}
void PrintList_prevtoend(struct ListNode** phead)
{
	assert(phead);
	struct ListNode* cur=*phead;
	printf_prevtoend(cur);
	printf("NULL\n");
}
int main()
{
    struct ListNode* phead=NULL;
    CreatListNode(&phead,1);
    CreatListNode(&phead,2);
    CreatListNode(&phead,3);
    CreatListNode(&phead,4);
    CreatListNode(&phead,5);
    Display(&phead);
    //RemoveNode(&phead,1);
    PrintList_prevtoend(&phead);
    //Display(&phead);
    Destory(&phead);
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值