初始化单链表,并在只遍历一次的情况下倒序
2011-11-24 23:00
399 查看
/*
初始化单链表,并在只遍历一次的情况下倒序
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
struct Node * nodeinit(void) //构建单链表
{
node *head,*p,*q;
head=(node*)malloc(sizeof node);
int x=0,n=0;
while(1)
{
printf("input the number:\n");
scanf("%d",&x);
if(x==0)
{
break;
}
else
{
p=(node *)malloc(sizeof node);
p->data=x;
if(++n==1)
{
head->next=p;
}
else
{
q->next=p;
}
q=p;
}
}
p->next=NULL;
return head;
}
void showlist(struct Node *head) //打印单链表
{
printf("the list is:\n");
struct Node *p=head->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
struct Node * resetlist(struct Node *head) //单链表倒序
{
printf("start reset!\n");
struct Node *p,*q;
p=head->next;
while(p!=NULL)
{
q=p;
p=p->next;
q->next=head->next;
if(q->next==q)
{
q->next=NULL;
}
head->next=q;
}
printf("success reset!\n");
return head;
}
int main()
{
struct Node *head1,*head2;
head1=nodeinit();
showlist(head1);
head2=resetlist(head1);
showlist(head2);
return 0;
}
初始化单链表,并在只遍历一次的情况下倒序
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
struct Node * nodeinit(void) //构建单链表
{
node *head,*p,*q;
head=(node*)malloc(sizeof node);
int x=0,n=0;
while(1)
{
printf("input the number:\n");
scanf("%d",&x);
if(x==0)
{
break;
}
else
{
p=(node *)malloc(sizeof node);
p->data=x;
if(++n==1)
{
head->next=p;
}
else
{
q->next=p;
}
q=p;
}
}
p->next=NULL;
return head;
}
void showlist(struct Node *head) //打印单链表
{
printf("the list is:\n");
struct Node *p=head->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
struct Node * resetlist(struct Node *head) //单链表倒序
{
printf("start reset!\n");
struct Node *p,*q;
p=head->next;
while(p!=NULL)
{
q=p;
p=p->next;
q->next=head->next;
if(q->next==q)
{
q->next=NULL;
}
head->next=q;
}
printf("success reset!\n");
return head;
}
int main()
{
struct Node *head1,*head2;
head1=nodeinit();
showlist(head1);
head2=resetlist(head1);
showlist(head2);
return 0;
}
相关文章推荐
- 一次遍历单链表中间节点
- 给出一个单链表,不知道节点N的值,怎样只遍历一次就可以求出中间节点,写出算法!
- 给出一个单链表,不知道节点N的值,怎么遍历一次就可以求出中间节点
- 编程之美读书笔记---单链表反序---要求只遍历一次
- 遍历一次反转单链表
- 逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表
- 编程之美读书笔记---单链表反序---要求只遍历一次
- 编程之美(一)单链表只遍历一次实现元素反转
- 查找单链表的中间节点,要求只能遍历一次链表
- 多线程情况下初始化一次(InitOnceExecuteOnce)
- 程序员面试宝典-遍历一次求出单链表的中间节点
- C语言:【单链表】查找单链表的中间节点,要求只能遍历一次
- 有关单链表的两个问题【遍历一次求中间节点,倒数第K个结点】
- 删除单链表的头元素;单链表,只是遍历一次,求出中间节点
- C语言:【单链表】查找单链表的倒数第k个节点,要求只能遍历一次
- 遍历一次单链表,找出单链表中间的值
- 查找单链表的中间节点,要求只能遍历一次链表
- 给一个单链表,不知道结点N的值,怎样只遍历一次就可以求出中间结点,写出算法
- 逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表
- 查找单链表的倒数第k个节点,要求只能遍历一次链表