遍歷一次把單鏈表反轉

遍歷一次把單鏈表反轉

#include <stdio.h>

#include <stdlib.h>


typedef struct student {
  int num;
  struct student *next;
}List;


List *creat_list(void)  /*創建鏈表,當輸入0的時候就結束*/
{
  int n = 0;
  List *head;
  List *p1,*p2;
  p1=p2=(List*)malloc(sizeof(struct student));
  scanf("%d",&p1->num);
  head = NULL;
  while(p1->num!=0)
    {
      n = n+1;
      if(1==n)
head = p1;
      else
p2->next = p1;
      p2 = p1;
      p1 = (List*)malloc(sizeof(struct student));
      scanf("%d",&p1->num);
    }
  p2->next = NULL;
  return head;



void print_list(List *head)  /*打印鏈表*/
{
  List *p;
  p = head;
  do{
    printf("num is:%d\n",p->num);
    p = p->next;
  }while(p);
}


List *reverse_list(List *head)/*反轉鏈表*/
{
  List *h,*cur,*fellow;  //h指向頭節點,cur指向當前節點,fellow指向當前節點的下一個
  h = head;
  cur = h->next;
  fellow = cur->next;
  h->next = NULL;   //設置鏈表的結尾
  while(cur)
    {
      cur->next = h;  //把當前節點的next指向h,
      h = cur;   //h向前推移
      cur = fellow;//當前節點指向下一個節點
      if(cur)//如果fellow不是NULL
      fellow = fellow->next;
    }
  return h;
}




int main(int argc, char **argv)
{
  List *h;
  List *head;
  h = creat_list();
  print_list(h);
  head = reverse_list(h);
  printf("After reverse:\n");
  print_list(head);
  return 0;
}
發佈了16 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章