链表的建立、输出、非递归反转、递归反转
代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <string.h>
#include <fstream>
#include <map>
#include <iomanip>
#include <cmath>
#include <set>
#include <stdio.h>
#include <queue>
using namespace std;
const int MAX = 0x7FFFFFFF;
const int MIN = 0x80000000;
typedef struct node
{
int value;
struct node *next;
}Node;
//功能:创建链表
//输入:头结点
//返回值:-1代表创建失败,1代表创建成功
int createList(Node** head)
{
int a, count = 0;
Node *cur, *pre;
//0为终止符
while(cin >> a && a != 0)
{
if(count == 0)
{
*head = (Node*)malloc(sizeof(Node));
if(*head == NULL)
return -1;
(*head)->value = a;
(*head)->next = NULL;
cur = pre = *head;
}
else
{
cur = (Node*)malloc(sizeof(Node));
if(cur == NULL)
return -1;
cur->value = a;
cur->next = NULL;
pre->next = cur;
pre = cur;
}
count++;
}
return 1;
}
//功能:打印链表
//输入:链表头结点
//返回值: -1代表链表为空,1代表打印成功
int printList(Node* head)
{
if(head == NULL)
return -1;
while(head != NULL)
{
cout << head->value << " ";
head = head->next;
}
cout << endl;
return 1;
}
//非递归反转链表
//输入:二级指针的头结点
//返回值:-1表示链表为空,1代表反转成功
//参数中的头结点为二级指针,函数完成之后,head指向反转后的结点
int reverseListNotRecursion(Node** head)
{
Node* cur, *pre = *head;
if(*head == NULL)
return -1;
while(pre->next != NULL)
{
cur = pre->next;
pre->next = cur->next;
cur->next = *head;
*head = cur;
}
return 1;
}
//递归反转链表
//输入:头结点,待反转结点
//返回值:当前反转的结点,已插入尾部
//返回为参数中的引用,即反转后的头结点
Node* reverseListRecursion(Node** head, Node* p)
{
Node* remain;
if(p == NULL || p->next == NULL)
{
*head = p;
return p;//返回最后一个结点
}
remain = reverseListRecursion(head, p->next);
remain->next = p;
p->next = NULL;
return p;
}
int main()
{
Node *head = NULL;
//建立链表
//假设创建链表中数依次为:1,2,3,4,5
createList(&head);
//输出创建之后的链表
//输出1 2 3 4 5
printList(head);
//非递归反转链表
reverseListNotRecursion(&head);
//输出5 4 3 2 1
printList(head);
//递归反转链表
reverseListRecursion(&head, head);
//输出1 2 3 4 5
printList(head);
system("pause");
return 0;
}