您的位置:首页 > 其它

链表的输入输出及逆转

2017-02-20 18:35 267 查看
对于链表,输入输出以及逆转是比较常见的,输入输出时可以根据自己的需要调整,我这写的c程序是输入一个链表的长度,然后输入链表各节点数据,最后输出顺序的数据以及逆序的数据。给了三个函数,分别是输入输出以及逆转的程序。

先给出一个输入输出函数:

#include<stdio.h>
#include<stdlib.h>
typedef struct node * List;
struct node
{
int data;
List next;
};

List read()
{
int len,num;
List first,second,third;
scanf("%d",&len);
scanf("%d",&num);
first=(List)malloc(sizeof(struct node));
first->data=num;
first->next=NULL;
second=first;
len--;
while(len--)
{
scanf("%d",&num);
third=(List)malloc(sizeof(struct node));
third->data=num;
third->next=NULL;
second->next=third;
second=third;
}
return first;
}

int main()
{
List L1;
L1=read();
while(L1->next!=NULL)
{
printf("%d ",L1->data);
L1=L1->next;
}
printf("%d\n",L1->data);
return 0;
}



运行如图。


单链表逆转也和上面类似,多了一个逆转过程:

#include <stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct Node * PtrToNode;
typedef PtrToNode List;
struct Node {
ElementType Data;
PtrToNode Next;
};

int main()
{
List Read();
void Print( List L );
List Reverse( List L ); //函数声明

List L1, L2;
L1 = Read();
Print(L1);
L2 = Reverse(L1); //如果将这一行和上面一行交换位置,就会不一样,输出L1的时候就会只有一个数。
Print(L2);
return 0;
}
List Read()
{
int len;
int num;
List list;
List last;
List node;
scanf( "%d",&len );
if( len == 0 )
return NULL;

scanf( "%d",&num );
list = ( PtrToNode )malloc( sizeof( struct Node ) );
list->Data = num;
list->Next = NULL;
last = list;
len--;
while( len-- ){
scanf( "%d",&num );
node= ( List )malloc(sizeof(struct Node));
node->Data = num;
node->Next = NULL;
last->Next = node;
last = node;
}
return list;
}
vo
4000
id Print( List L )
{
if(L==NULL)
return ;
else
while(L!=NULL){
printf("%d ",L->Data);
L=L->Next;
}
putchar('\n');
}
List Reverse( List L ){
PtrToNode t=NULL;
PtrToNode newlist=NULL;
while(L!=NULL){
t=L->Next; //用t保存L的下一个节点,否则L->next就丢失了,方便L的移动
L->Next=newlist;//L指向它的前一个节点
newlist=L; //newlist指向已经逆转的最后一个节点
L=t; //将L移动到下一个元素
}
return newlist;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐