zoukankan      html  css  js  c++  java
  • 反转链表

    输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。

    利用三个指针来翻转,代码如下

    //翻转链表
    #include<iostream>
    using namespace std;
    struct list{
    	int data;
    	list* next;
    };
    list* create_list(void){
    	list *current=new list;
    	current->data=1;
    	current->next=NULL;
    	list *head=current;
    	for(int i=2;i<=10;i++){
    		list * p=new list;
    		p->data=i;
    		p->next=NULL;
    		current->next=p;
    		current=p;
    	}
    	return head;
    }
    list* list_reverse(list *headNode){
    	list *node=headNode;
    	list *last=NULL;              //记录前面的已经翻转好的表头
    	list *reverse_head=NULL;      //翻转后的表头
    	while(node){
    		list *link=node->next;
    		if(!link) reverse_head=node;
    		node->next=last;            //利用三个指针翻转
    		last=node;
    		node=link;
    		//cout<<last->data<<endl;
    	}
    	return  reverse_head;
    }
    void print(list *headNode){
    	while(headNode){
    		cout<<headNode->data<<" ";
    		headNode=headNode->next;
    	}
    	cout<<endl;
    }
    int main(void){
    	list *head=create_list();
    	print(head);
    	print(list_reverse(head));
    	system("pause");
    	return 0;
    }
    

  • 相关阅读:
    hdu 1392 凸包周长
    hdu 1847
    时间管理101招
    祝大家端午节快乐
    激励员工的二十种非经济手段
    Web2.0个人桌面
    回顾Windows系列的OEM版本历史
    什么是电子商务
    解析3G软件人才成功之道
    成功者应具备的八个心态
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/1959211.html
Copyright © 2011-2022 走看看