链表(一)链表的新建、反转、释放

#include <iostream>
using namespace  std;
//创建一个链表,释放链表的内存,将链表反转
//链表翻转需要三个指针:头 中 后
typedef struct node
{
	struct node *next;
	int num;
}Node;
Node * create(int num);
void print(Node *head);
void freeNode(Node *&head); //这里参数是指针的引用
Node *inverse(Node *head);
//如果不直接使用指针的引用的时候,函数体外的head并没置NULL,导致在print中引用了已经释放的变量;
int main()
{
	Node *head=create(15);
	print(head);
	print(inverse(head));


	freeNode(head);
	print(head);
	getchar();
}

Node * create(int num)//产生长度为num的链表
{
	Node *head=new Node;
	head->num=0;
	Node *temp=head;
	for(int i=1;i<num;i++)
	{
		temp->next=new Node;
		temp=temp->next;
		temp->num=i;
	}
	temp->next=NULL;
	return head;
}

// 释放head对应的链表,会每个节点的释放
//类似于过河拆桥,从表头开始释放
//对指针的释放只是把那块内存还给操作系统,指针中存的地址还是那块
//因而要记得将指针重置NULL
//参数是关于指针的引用 Node * &head
void freeNode(Node *&head)  
{
	if(head==NULL)
	{
		return;
	}
	Node *temp=head;
	Node *tempNext=NULL;
	while (temp->next!=NULL)
	{	
		tempNext=temp->next;
		delete temp;
		temp=NULL;
		temp=tempNext;
	}
	delete temp;
	head=NULL;

}
void print(Node *head)
{
	if(head==NULL)
		return;

	Node *temp=head;
	while(temp->next!=NULL)
	{
		cout<<temp->num<<"\t";
		temp=temp->next;
	}
	cout<<temp->num<<"\t";
	cout<<endl;


}
//单向链表逆转
Node *inverse(Node *head)
{
	if(head==NULL||head->next==NULL)
	{
		return head;//只有一个节点或者没有节点的情况
	}
	Node *temp=head;
	Node *tempNext=temp->next;
	Node *temp2=NULL;
	while(tempNext->next!=NULL)//找到倒数两个尾节点
	{//这里至少三个节点
		temp2=temp;
		temp=tempNext;
		tempNext=tempNext->next;
		temp->next=temp2;
	}
	tempNext->next=temp;
	head->next=NULL;
	//tempNext这是尾巴节点,即新的头结点
	return tempNext;	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值