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;
}
}