zoukankan      html  css  js  c++  java
  • 链表的倒序输出

    链表的倒序输出,我们可能想到的方法就是把链表翻转后然后再遍历一遍,这种话时间复杂度是O(n),可是缺点是代码略微复杂。

    或者是开辟一个数组,顺序遍历一个链表把元素拷贝到数组里面,最后再把数组倒序输出。事实上这道题目时间复杂度都不可能低于O(n),可是考虑用栈的话代码就可能很easy,代码例如以下所看到的:

    #include <iostream>
    using namespace std;
    
    struct Node
    {
    	int key;
    	Node* next;
    };
    
    Node* createList(int arr[],int nLength);
    void printList(Node* head);
    void reversePrint(Node* head);
    void clearList(Node* head);
    
    void main()
    {
    	int arr[] = {1,3,5,7,9};
    	int nLength = sizeof(arr)/sizeof(arr[0]);
    	Node* head = createList(arr,nLength);
    	printList(head);
    	reversePrint(head);
    	clearList(head);
    }
    
    Node* createList(int arr[],int nLength)
    {
    	Node* head = new Node;
    	head->key = arr[0];
    	head->next = NULL;
    	Node *p = head;
    	for(int i=1;i<nLength;i++)
    	{
    		Node* ptr = new Node;
    		ptr->key = arr[i];
    		ptr->next = NULL;
    		p->next = ptr;
    		p = p->next;
    	}
    	return head;
    }
    
    
    void printList(Node* head)
    {
    	Node* p = head;
    	while( p!= NULL )
    	{
    		cout<<p->key<<endl;
    		p=p->next;
    	}
    }
    
    void clearList(Node* head)
    {
    	Node* p = head;
    	Node* ptr;
    	while( p!= NULL )
    	{
    		ptr = p->next;
    		delete p;
    		p = ptr;
    	}
    }
    
    void reversePrint(Node* head)
    {
    	if( head != NULL )
    	{
    		if( head->next != NULL )
    			reversePrint(head->next);
    	}
    	cout<<head->key<<endl;
    }


  • 相关阅读:
    模拟乒乓球双打和单打比赛
    关于zip内置函数的应用及在 Python 2 和 3 的不同之处
    计算文本平均列数
    四则运算
    Python跳一跳小游戏
    数据库
    类和正则表达
    带进度条的圆周率计算
    球队预测
    自己的第一个网页
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6871844.html
Copyright © 2011-2022 走看看