zoukankan      html  css  js  c++  java
  • 反向输出链表

    1、问题描述

    定义一个数据结构,并且反向输出单向链表。

    2、代码

    #include <iostream>  
    #include <vector>  
    #include <iterator>  
    #include <cassert>  
    #include<algorithm>//copy  
    using namespace std;  
    const int n=2;  
    struct node  
    {  
    	int i;  
    	node *next;  
    };  
    node *Reverse(node *head)  
    {  
    	//判断链表是否为空  
    	assert(head != NULL &&  " function Reverse : list is null!");  
    	node *temp=head->next;  
    	//链表只有一个元素情况  
    	if(temp == NULL ) return head;  
    	//链表翻转前head-->temp-->tail,翻转后tail-->temp-->head  
    	head->next=NULL;  
    	node *tail=temp->next;  
    	while(tail != NULL)  
    	{  
    		temp->next=head;  
    		head=temp;  
    		temp=tail;  
    		tail=tail->next;  
    	}  
    	temp->next=head;  
    	//返回翻转后的链表头指针  
    	return temp;  
    }  
    void Print(node *head)  
    {  
    	while(head != NULL)  
    	{  
    		cout<<head->i<<"  ";  
    		head=head->next;  
    	}  
    	cout<<endl;  
    }  
    int main()  
    {  
    	node *head=NULL,*tail=NULL,*temp=NULL;  
    	head= new node;  
    	head->i=1;head->next=NULL;  
    	tail=head;  
    	for(int i=2;i<=n;++i)  
    	{  
    		temp =new node;  
    		temp->i=i;temp->next=NULL;  
    		tail->next=temp;  
    		tail=temp;  
    	}  
    	Print(head);  
    	cout<<"------------"<<endl;  
    	head=Reverse(head);  
    	Print(head);  
            
    	return 0;  
    }  
    

      

  • 相关阅读:
    bzoj2438
    bzoj3040
    [AHOI2009]维护序列
    [JSOI2008]最大数
    洛谷3378堆模板
    洛谷1439
    洛谷2756
    bzoj1016
    洛谷1875
    [模板] 强连通分量
  • 原文地址:https://www.cnblogs.com/yedushusheng/p/5519207.html
Copyright © 2011-2022 走看看