单链表的反转 c++
2013-04-15 14:37
411 查看
#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
={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++反转单链表后半部分
- 剑指offer刷题之c++实现的反转链表
- 【C++】反转链表
- C++笔试题之实现单链表反转
- (C++)剑指offer-15:反转链表(代码的鲁棒性)
- 【编程题目】反转链表(C++实现)
- 1025. 反转链表 (25)(C++)
- c++实现单向链表反转的学习总结
- c++反转整个链表
- C++链表K个节点K个节点的反转((1,2,3,4),如果k是2,反转结果是(2,1,4,3))
- 【C++】PAT(basic level)1025. 反转链表 (25)
- C++递归与非递归实现链表的反转
- c++初级 之 反转链表
- 递归,迭代,堆栈三种方式实现单链表反转(C++)
- c++之链表篇2:单向链表的反转(详细图文解读)
- 【链表】C++链表反转、链表逆序打印
- 数据结构 - 反转单链表(C++)
- 链表反转C++
- C++将链表反转的实现
- 剑指offer第十五题【反转链表】c++实现