单向链表初始化以及链表逆序

1、两种初始化的方法

2、逆序排列一个单向链表

//实现节点逆序
#include <stdio.h> 
#include<iostream>
#include<stdlib.h>
using namespace std;

typedef struct Node
{
	int data;
	struct Node *next ;
}myNode;
Node * reverse(Node * head);
Node * initNodeH();
Node * initNodeT();
void printNode(Node *head);
int main(int arg,char * argv[]){
	
	
	for (int i = 0; i < 2; i++)
	{
		
		Node * tHead = nullptr;
		if (i == 0)
		{
			 tHead = initNodeT();
		}
		else
		{
			 tHead = initNodeH();
		}
		cout<<"逆序打印链表"<<endl;
		tHead = reverse(tHead);
		printNode(tHead);


		cout<<"释放空间"<<endl;
		//释放链表空间
		while (tHead != nullptr)
		{
			Node * tmp = tHead;
			tHead = tHead->next;
			if (tmp != nullptr)
			{
				free(tmp);
				tmp = nullptr;
			}

		}
		cout<<endl<<endl;
	}
	

	system("pause");
	return 0;
}
//头插链表
Node * initNodeH(){
	
	Node * tmpHead = (Node *)malloc(sizeof(Node));
	tmpHead->data = -1;
	tmpHead->next = nullptr;
	for (int i = 9; i >= 0; i--)
	{
		Node * NextNode = (Node *)malloc(sizeof(Node));
		NextNode->data = i;
		NextNode->next = tmpHead->next;
		tmpHead->next = NextNode;
	}
	cout<<"*****************************************头插法*****************************************"<<endl;
	Node * head = tmpHead->next;
	tmpHead->next = nullptr;
	printNode(head);
	return head;
} 
//尾插法初始化链表
Node * initNodeT(){

	Node * tmphead = (Node *)malloc(sizeof(Node));
	
	tmphead->next = nullptr;

	Node * tmpTail = tmphead;
	for (int i = 0; i < 10; i++)
	{
		Node * LastNode = (Node *)malloc(sizeof(Node));
		LastNode->data = i;

		tmpTail->next = LastNode;
		tmpTail = LastNode;
	}
	tmpTail->next = nullptr;

	//输出链表
	//头节点
	Node *tNode = tmphead->next;
	Node * headNode = tNode;
	cout<<"*****************************************尾插法*****************************************"<<endl;
	printNode(headNode);
	tmphead->next = nullptr;
	return headNode;
}

//逆序排列链表
Node * reverse(Node * head){
	Node * first = head;
	Node * second = head;
	Node * tmp = head;
	
	//是否是空链表判定
	if (head == nullptr)
	{
		cout<<"head is NUll,空链表"<<endl;
		return nullptr;
	}
	
	//逆序链表
	second = first->next;
	while (second != nullptr)
	{
		tmp = second->next;
		second->next = first;

		
		first = second;
		second = tmp;
	}
	head->next = nullptr;

	return  first;
}

void printNode(Node *head){
	//输出链表
	Node *tNode = head;
	while (tNode != nullptr)
	{
		cout<<tNode->data<<endl;
		tNode = tNode->next;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值