单链表反转

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值