实验二、3链表的就地逆置

来源:互联网 发布:windows 7死亡倒计时 编辑:程序博客网 时间:2024/05/01 18:35

昨晚写的 呵呵

创建一个链表 然后就地逆置

和上一个实验目的一样 但是这个是链表 上个是顺序表

#include<stdio.h>
#include<stdlib.h>
#define  null 0
#define LEN sizeof(struct stu)
#define elemtype int
typedef struct stu//定义结构体
{
 elemtype date;
 struct stu*next; 
}llist;
llist *creatlist(int n)
{
 llist *head=null,*s,*p;
 int i;
 for(i=0;i<n;i++)//创建含n个结点的链表
 {
  p=(llist*)malloc(LEN);
  printf("please input the date:");
  scanf("%d",&p->date);
  if(i==0)
  {
   head=p;
   s=p;
   head->next=null;
  }
  else
  {
   s->next=p;
   s=p; 
  } 
 }
 p->next=null;//最后一个应当设置为null
 return(head);
}
void printlist(llist *head)//正常输出表
{
 llist *p;
 p=head;
 printf("基本线性表是:/n");
 while(p!=null)
 {
  printf("%d->",p->date);
  p=p->next; 
 }
}
llist *revelist(llist *head)//表的就地逆置
{
 llist *p,*q;
 if(head&&head->next)
 {
  p=head;
  q=p->next;
  p->next=null;//断开两个表
  while(q)
  {
   p=q;
   q=q->next;
   p->next=head;
   head=p; 
  }
 }
 return(head);
}
int main()
{
 llist *head=null,*p;
 int n,num;
 printf("please input the number of node:");
 scanf("%d",&n);
 head=creatlist(n);//creat list 
 printf("Before reverlist:/n");
 printlist(head);
 printf("/n");
 p=revelist(head);
 printf("After revelist:/n");
 printlist(p);
 printf("/n");
 system("pause");
}
 

原创粉丝点击