将单链表H逆置
2015-11-07 21:14
411 查看
逆置:是指节点间的关系相反,即前驱变后继而后继变前驱。
算法思路:
依次从原链表中取出每个节点,每次都把该节点作为第一个节点插入另一个新链表中。#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
struct node{
int data ;
struct node * next ;
} ;
//建立单链表,返回头结点
struct node * CreateLinkList(){
char ch ;
int x ;
struct node * head ;
struct node * r , * P ;
head = (struct node *)malloc(sizeof(struct node)) ;
head->next = NULL ;
r = head ;
ch =getchar( ) ;
while(ch != '*'){
// cout<<"ch = " << ch<< endl;
scanf("%d" , & x) ;
// cout<<"x = " << x << endl;
P = (struct node *) malloc(sizeof(struct node)) ;
P->data = x ;
P->next = NULL ;
r->next = P ;
r = r-> next ;
ch = getchar( ) ;
}
return head ;
}
//将单链表head逆置,并返回逆置后的链表
struct node * reverseLinkList(struct node * head ){
struct node *f , * b , *r;
// b = (struct node *)malloc(sizeof(struct node));
f = head->next;
b->next = NULL ;
head->next = NULL ;
while(f != NULL){
r = f ; //取节点
// cout<<"f->data = "<< f->data << endl;
// cout<<"f->next = " << f->next << endl;
f = f->next ;
r->next = b->next ; //插入节点
b->next = r ;
}
return b ;
}
int main(){
cout<< "建立单链表(请输入:[空格]25 45 18 76 29*)"<< endl;
struct node * rr =CreateLinkList();
PutOut(rr) ;
struct node * qq ;
cout<<"输出逆置的单链表"<< endl;
qq = reverseLinkList(rr) ;
PutOut(qq) ;
return 0 ;
}
算法思路:
依次从原链表中取出每个节点,每次都把该节点作为第一个节点插入另一个新链表中。#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
struct node{
int data ;
struct node * next ;
} ;
//建立单链表,返回头结点
struct node * CreateLinkList(){
char ch ;
int x ;
struct node * head ;
struct node * r , * P ;
head = (struct node *)malloc(sizeof(struct node)) ;
head->next = NULL ;
r = head ;
ch =getchar( ) ;
while(ch != '*'){
// cout<<"ch = " << ch<< endl;
scanf("%d" , & x) ;
// cout<<"x = " << x << endl;
P = (struct node *) malloc(sizeof(struct node)) ;
P->data = x ;
P->next = NULL ;
r->next = P ;
r = r-> next ;
ch = getchar( ) ;
}
return head ;
}
//将单链表head逆置,并返回逆置后的链表
struct node * reverseLinkList(struct node * head ){
struct node *f , * b , *r;
// b = (struct node *)malloc(sizeof(struct node));
f = head->next;
b->next = NULL ;
head->next = NULL ;
while(f != NULL){
r = f ; //取节点
// cout<<"f->data = "<< f->data << endl;
// cout<<"f->next = " << f->next << endl;
f = f->next ;
r->next = b->next ; //插入节点
b->next = r ;
}
return b ;
}
int main(){
cout<< "建立单链表(请输入:[空格]25 45 18 76 29*)"<< endl;
struct node * rr =CreateLinkList();
PutOut(rr) ;
struct node * qq ;
cout<<"输出逆置的单链表"<< endl;
qq = reverseLinkList(rr) ;
PutOut(qq) ;
return 0 ;
}
相关文章推荐
- 反转链表
- 单链表的逆置
- 反转链表(在原链表进行操作,不开辟新空间. O(N)
- 链表面试题(一):逆序打印链表、无头链表删除插入节点、约瑟夫环、逆置单链表
- 链表只翻转一部分
- 206. Reverse Linked List
- 数据结构实验之链表三:链表的逆置
- 单向链表常见的笔试面试题
- 剑指offer--链表逆置
- ACM程序设计,找出可疑串,并删除可疑串,用C++实现
- Qt在Windows下的三种编程环境搭建
- A*算法解决八数码(九宫重排)问题
- 循环队列
- Python编写微信打飞机小游戏(一)
- redis3.0.2 编译安装(启动参数方式启动)
- 写一个遍历指定目录下所有子文件的函数
- (自动补全代码)Win7平台VS2010安装Visual Assist X
- 获取网络上的图片,并显示在界面上的简单实现
- uva 1617——Laptop
- java中的private static变量的小心得