#include<iostream>
#include<string>
using namespace std;
typedef struct Node
{
int val;
Node* next;
}*pNode;
void print_list(pNode head)
{
pNode tmp = head;
while(tmp)
{
std::cout<<tmp->val<<" ";
tmp = tmp->next;
}
std::cout<<std::endl;
}
void insert_list(pNode& head, int* arr, int len)
{
pNode tmp = head;
if(NULL == head)
{
head = new Node;
head->next = NULL;
tmp = head;
}
else
{
while(tmp->next)
{
tmp = tmp->next;
}
}
for(int index = 0x00; index < len; index++)
{
pNode node = new Node;
node->val = arr[index];
tmp->next = node;
node->next = NULL;
tmp = node;
}
}
void destroy_list(pNode& head)
{
pNode tmp = head;
while(tmp)
{
pNode p = tmp->next;
delete tmp;
tmp = p;
}
}
pNode reverse_list(pNode& head, pNode curNode)
{
if(curNode && curNode->next == NULL)
{
head = curNode;
return curNode;
}
pNode tmp = reverse_list(head, curNode->next);
tmp->next = curNode;
curNode->next = NULL;
return curNode;
}
void rev_list(pNode& head)
{
if(!head)
return ;
pNode tmp = head;
pNode p2 = head->next;
while(p2)
{
pNode p3 = p2->next;
p2->next = head;
head = p2;
p2 = p3;
}
tmp->next = NULL;
}
int main()
{
pNode head = new Node;
head->val = 1000;
head->next = NULL;
int arr[10] = {0x00};
for(int index = 0x00; index < 10; index++)
arr[index] = index+0x01;
insert_list(head, arr,10);
print_list(head);
#if 0x01
reverse_list(head, head);
#else
rev_list(head);
#endif
print_list(head);
destroy_list(head);
return 0x00;
}
单链表反转
最新推荐文章于 2022-01-20 19:47:26 发布