单链表的逆置
2015-10-11 17:10
260 查看
1,算法描述:实现带头结点的单链表的逆置。
代码如下:
#include<stdio.h>
#include <malloc.h>
typedef struct LNode
{
int data;
LNode *next;
}LNode,*LinkList;
//creat a LinkList
bool creatLinklist(LinkList&L,int n)
{
LinkList p,q,t,s;
L=(LNode*)malloc(n*sizeof(LNode));
if(!L)
return false;
q=L;
for(int i=1;i<=n;i++)
{
p=(LNode*)malloc(sizeof(LNode));
scanf("%d",&p->data);
L->next=p;
L=p;
}
p->next=NULL;
L=q;
return true;
}
bool inversLinkList(LinkList&L)
{
LinkList p,q,t;
p=L->next;//The first Node
q=p->next;//The second Node
p->next=NULL;
while(q)
{
t=q->next;// keep the third Node
q->next=p;// the second Node points to the first Node in a loop
p=q; //p points to next Node
q=t; //q points to next Node
}
L->next=p; //set head Node
return true;
}
void main()
{
LinkList Llist,p;
int k;
int elemet;
int position;
printf("input the number of LinkList to be created:");
scanf("%d",&k);
creatLinklist(Llist,k);
printf("\n");
inversLinkList(Llist);
printf("output the new LinkList:\n");
p=Llist->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
free(Llist);
}运行结果如下:
代码如下:
#include<stdio.h>
#include <malloc.h>
typedef struct LNode
{
int data;
LNode *next;
}LNode,*LinkList;
//creat a LinkList
bool creatLinklist(LinkList&L,int n)
{
LinkList p,q,t,s;
L=(LNode*)malloc(n*sizeof(LNode));
if(!L)
return false;
q=L;
for(int i=1;i<=n;i++)
{
p=(LNode*)malloc(sizeof(LNode));
scanf("%d",&p->data);
L->next=p;
L=p;
}
p->next=NULL;
L=q;
return true;
}
bool inversLinkList(LinkList&L)
{
LinkList p,q,t;
p=L->next;//The first Node
q=p->next;//The second Node
p->next=NULL;
while(q)
{
t=q->next;// keep the third Node
q->next=p;// the second Node points to the first Node in a loop
p=q; //p points to next Node
q=t; //q points to next Node
}
L->next=p; //set head Node
return true;
}
void main()
{
LinkList Llist,p;
int k;
int elemet;
int position;
printf("input the number of LinkList to be created:");
scanf("%d",&k);
creatLinklist(Llist,k);
printf("\n");
inversLinkList(Llist);
printf("output the new LinkList:\n");
p=Llist->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
free(Llist);
}运行结果如下:
相关文章推荐
- rhel7 升级内核,保证grub2启动时为默认项目
- 程序员书单合集,持续整理中
- lintcode 容易题 :Singleton 单例
- java8 stream学习笔记
- 【Python】Learn Python the hard way, ex20 用函数读文件readline
- c++读取txt中每行的数据到数组中
- $.ajax({...});异步请求问题
- 对web应用中单一入口模式的理解及php实现
- std::min&std::max与mfc冲突问题
- html5烟花绽放效果
- vim高级功能入门
- std::min&std::max与mfc冲突问题
- 程序的机器级表示
- hihocoder #1015 KMP算法
- 机房中的 PING
- 编程疑难点
- 圣杯布局与双飞翼布局的实现&区别
- hdoj 5501 The Highest Mark 【贪心 + 0-1背包】
- hdoj 5500 Reorder the Books 【好题】
- rhel7 设置带sgid的目录权限