链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
2011-10-26 19:39
357 查看
常见的三指针方法
struct node {
int data;
node * next;
};
node* inverseList(node *head){
if(head==NULL||head->next==NULL) return head;
node *pre = NULL;
node *cur = head;
node *next =NULL;
while(cur&&cur->next){
if(pre){
pre->next = cur->next;
}else{
head = cur->next;
}
pre = cur;
next = cur->next->next;
cur->next->next = cur;
cur->next = next;
cur = next;
}
return head;
}
node* createList(){
node* head=NULL;
node* cur=NULL;
node* pn;
for(int i=0;i<100;++i){
pn = new node;
pn->data = i;
if(cur==NULL)
{
head = pn;
cur = pn;
}else{
cur->next = pn;
cur = pn;
}
cur->next = NULL;
}
return head;
}
node* deleteList(node* head){
if(head==NULL) return NULL;
node * cur = head;
node * next = NULL;
while(cur){
next = cur->next;
delete cur;
cur = next;
}
return NULL;
}
void printList(node* head){
if(head){
printf("%d",head->data);
}
head = head->next;
while(head){
printf("->%d",head->data);
head = head->next;
}
printf("\r\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
node *head=createList();
printList(head);
head = inverseList(head);
printList(head);
deleteList(head);
}
struct node {
int data;
node * next;
};
node* inverseList(node *head){
if(head==NULL||head->next==NULL) return head;
node *pre = NULL;
node *cur = head;
node *next =NULL;
while(cur&&cur->next){
if(pre){
pre->next = cur->next;
}else{
head = cur->next;
}
pre = cur;
next = cur->next->next;
cur->next->next = cur;
cur->next = next;
cur = next;
}
return head;
}
node* createList(){
node* head=NULL;
node* cur=NULL;
node* pn;
for(int i=0;i<100;++i){
pn = new node;
pn->data = i;
if(cur==NULL)
{
head = pn;
cur = pn;
}else{
cur->next = pn;
cur = pn;
}
cur->next = NULL;
}
return head;
}
node* deleteList(node* head){
if(head==NULL) return NULL;
node * cur = head;
node * next = NULL;
while(cur){
next = cur->next;
delete cur;
cur = next;
}
return NULL;
}
void printList(node* head){
if(head){
printf("%d",head->data);
}
head = head->next;
while(head){
printf("->%d",head->data);
head = head->next;
}
printf("\r\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
node *head=createList();
printList(head);
head = inverseList(head);
printList(head);
deleteList(head);
}
相关文章推荐
- 链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
- 链表相邻元素翻转,如1->2->3->4->5->6-7,翻转后变为:2->1->4->3->6->5->7。
- 链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
- 链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
- 链表相邻元素翻转
- 链表相邻元素翻转
- 链表相邻元素翻转
- 链表相邻元素翻转
- 链表相邻元素翻转
- 链表相邻元素翻转
- 链表相邻元素翻转
- 算法 链表相邻元素翻转
- 链表的相邻元素的翻转
- C++循环链表中进行元素的翻转
- 链表遍历打印 翻转及 插入元素
- 链表相邻元素反转
- 链表:调换相邻元素
- Remove Duplicates from Sorted List ,除去链表中相邻的重复元素
- 数据结构实例<三>(匹配链表所有元素删除后并返回新的链表)入门
- 【C++ Primer】【练习题】【3.13】【3.17】求vector<int>相邻元素的和