实现单链表逆置
2013-10-08 17:13
106 查看
看到笔试和面试里很多这样的题目,于是就练习一下,温故知新。
上面逆置算法也可以这样写:
截图:
#include <iostream> #include <cstdlib> using namespace std; typedef struct List { int data; struct List *next; }listNode,*pList; void createList(pList & list) //头插入法建立单链表 { pList head=NULL; int data; cout<<"please input a node:"; cin>>data; list=(struct List *)malloc(sizeof(listNode)); list->data=data; list->next=head; head=list; while(data!=9) { cout<<"please input a node:"; cin>>data; list=(struct List*)malloc(sizeof(listNode)); list->data=data; list->next=head; head=list; } } void display(pList list) //输出单链表 { pList temp; temp=list; while(temp!=NULL) { if(temp->next==NULL) cout<<temp->data; else cout<<temp->data<<"->"; temp=temp->next; } cout<<endl; } void reverseList(pList& list) //逆置单链表 { pList pre; pList temp; pre=list->next; //记录当前节点 temp=pre->next; //记录下一个节点 list->next=NULL; while(pre!=NULL) { pre->next=list; list=pre; pre=temp; if(pre!=NULL) temp=temp->next; else break; } // pre->next=list; // list=pre; } int main() { pList list=NULL; cout<<"create the list :"<<endl; createList(list); cout<<"output the list:"<<endl; display(list); cout<<endl; cout<<"reverse the List:"<<endl; reverseList(list); cout<<"output the reverse list:"<<endl; display(list); cout<<endl; return 0; }
上面逆置算法也可以这样写:
void reverseList(pList& list) //逆置 { pList pre; pList temp; pre=list->next; //记录当前节点 temp=pre->next; //记录下一个节点 list->next=NULL; while(temp!=NULL) { pre->next=list; list=pre; pre=temp; temp=temp->next; } pre->next=list; list=pre; }
截图:
相关文章推荐
- 使用STL之list实现链表逆置
- c++中的双向链表写法,主要实现(增删查改,链表逆置,构造函数,运算符重载,等)
- 单链表逆序生成及逆置的完整实现
- 单向链表逆置的功能实现
- 实现单向循环链表的创建、测长、打印、插入、删除及逆置
- 实现就地逆置单链表
- 面试-链表逆置 作业手写一个单链表,并且实现单链表元素的逆置,(a0, a1,a2,a3,..an)-> (an,an-1,… a1, a0),算法的空间复杂度和时间复杂度经可能低
- 单链表的逆置-C++实现(转载)
- 文章标题 C语言实现单链表之逆置和逆序打印
- 链表(LinkList)的设计与实现(初始化,创建,插入,删除,逆置)
- 逆置单链表,C++封装实现,经过测试。
- 单链表的逆置-C++实现
- 左神的书——《程序员代码面试指南》之逆置单链表或双链表 c++实现
- 不开辟新内存,实现链表的就地逆置
- 倒插法实现链表逆置
- 数据结构-链表逆置(c++模板类实现)
- 如何实现单向链表的逆置
- 手写单链表-并实现单链表元素逆置
- 单链表逆置 递归实现
- 单链表(二):如何实现单链表的排序、逆置(逆序)