单链表的反转 c++
来源:互联网 发布:杨幂 知乎 编辑:程序博客网 时间:2024/04/29 13:11
#include<iostream>
#include<stdexcept>
using namespace std;
const int N=10;
typedef struct node
{ int key;
struct node*next;
} NODE;
// INSERT A ELEMENT INTO A LINKLIST
bool insert(NODE*p,int position,int key)//insert an elemnt which will be the position-th element of the linklist;if fail to insert an element return false otherwise return true;position:1,2,3~~~~~~~
{ if(NULL==p)
{cout<<"the linklist do not exist!";
return false;
}
else
{
int i=0;
NODE*p_find=p;//we will insert a new node following the node which is pointed by f_find
NODE*p_new=NULL;
while((i<position-1)&&p_find->next!=NULL)
{ p_find=p_find->next;
++i;
}
if(i!=position-1)// indicate that fail to find the position!
return false;
else
{ try
{ p_new=new NODE;
}
catch(bad_alloc)
{ cout<<"There is not enough memory to be allocated"<<endl;
return false;
}
p_new->key=key;
p_new->next=p_find->next;
p_find->next=p_new;
return true;
}
}
}
NODE*create_empty_linklist() //create a new empty linklist
{ NODE*p=NULL;
try{p=new NODE;
}
catch(bad_alloc)
{ cout<<"there is no enough memory to be allocated ";
return NULL;
}
p->next=NULL;
return p;
}
void free_all_linklist(NODE*p)// free all the node in a linklist
{ NODE*pp=NULL;
while(p!=NULL)
{ pp=p->next;
delete p;
p=pp;
}
}
/************反转链表的程序************************/
/************反转链表的程序************************/
void reverse_linklist(NODE*p)// reverse a linklist; example:from head_node->1->2->3->4 to head_node->4->3->2->1
{ if(NULL!=p)
{ NODE*p1=NULL,// 指向要反转的节点的前一个node,初始化必须为NULL;因为第一个节点的next域应该为NULL
*p2=p->next,//要反转的node,p2被初始化为链表的第一个节点
*p_save=NULL;//保存指向要反转的node的下一个节点的指针,因为反转后链表断裂,若不保存无法继续迭代
while(NULL!=p2)
{ p_save=p2->next;
p2->next=p1;//反转指针
p1=p2;//移动p1
p2=p_save;
}
p->next=p1;//头节点指向原来的尾元素
}
else
throw runtime_error("the linklist needed to be reversed is NULL!");
}
/************反转链表的程序************************/
/************反转链表的程序************************/
void iter_print(const NODE*head)//打印链表
{ const NODE*p=head->next;
while(p!=NULL)
{cout<<p->key<<" ";
p=p->next;
}
cout<<endl;
}
int main(void)
{ int a[N]={1,2,3,4,5,5,5,6,7,7},
i=0;
NODE*head=create_empty_linklist();
for(;i<N;++i)
insert(head,1,a[i]);
iter_print(head);
reverse_linklist(head);
iter_print(head);
free_all_linklist(head);
return 0;
}
- 单链表的反转实现(C++)
- C语言:单链表的反转
- C语言反转单链表
- 单链表反转 c实现
- 单链表反转C代码
- C语言反转单链表
- 单链表反转(C++)
- 反转单链表(C)
- C语言中链表的反转
- c/c++单链表的创建和删除,插入,反转操作
- 【C++】反转单链表(面试的时候屡次被问到)
- 数据结构 - 反转单链表(C++)
- 单链表反转C语言实现
- 单链表反转(C代码)
- 单链表反转C语言实现
- 单链表反转C语言实现
- C:单链表反转(循环)
- 单链表的反转
- Android Hardware Decoding with MediaCodec
- 集合处理成字符串
- Android Lint(官方代码优化利器)
- 血腥暴力太激情?被删减的N个电影镜头
- uva_100The 3n + 1 problem( DP )
- 单链表的反转 c++
- GSL 1.15 for windows 编译
- Java 单例模式详解
- 一个直观感性的方法认识linux的系统驱动架构
- 看查cpu内核个数
- 结构型模式之享元模式(Flyweight)
- 软解码创建softDecoder
- oracle9i与oracle10g的dmp文件互相导入规则
- XML,XSD,XSL