鏈表的輸入輸出以及就地逆轉

鏈表是個好東西,分享出來記錄在這裏,方便查找。

另外如struct member * list新建節點要賦值的時候,必須先分配內存空間list = (struct member *)malloc(sizeof(struct member))

然後才能賦值list->data = xxxx;

/*20131215 Denyz 鏈表是輸入輸出及就地逆轉*/ 
#include <stdio.h>
#include <malloc.h>

typedef struct{
        int num;
        int name;
        }Elementype;
        
typedef struct LinkList{
        Elementype elem;
        struct LinkList *next;
        }LList;

/*鏈表的創建i個元素,返回Head指針*/
LList *CreatList(int length)
{     
      int i=0,data;
      LList *Head,*PL,*PLn;
   printf("Input the Link List:\n");
      Head = (LList *)malloc(sizeof(LList));
      
   PL=Head->next=(LList *)malloc(sizeof(LList));//第一個結點
   scanf("%d",&PL->elem.num);
   PL->next=NULL;

      for(i=1;i<length;i++)
      {
          PLn=(LList *)malloc(sizeof(LList));//
          scanf("%d",&data);
          PLn->elem.num=data; 
    PLn->next=PL->next;
    PL->next=PLn;//將新結點接入鏈表
    PL=PLn;                                            
      }
      
      return Head;
}
 
//線性鏈表就地逆轉函數,用“砍頭”法
//砍斷頭結點後,在頭結點和Head指針的中間不斷插入鏈表的結點,從而達到鏈表逆轉的目的
void Reverse(LList *Head)
{
 LList *PL1,*PLn,*Tmp;
 PL1=Head->next;
 PLn=PL1->next;//先保存頭結點後面一個結點的指針,不然頭結點砍斷後將丟失後面的結點
 PL1->next=NULL;//砍斷第一個結點,也就是頭結點
 
 while(PLn)
 {
  Tmp=PLn->next;//用Tmp保存當前結點的next結點的指針,確保砍斷當前結點後丟失後面的結點。
  PLn->next=PL1;
  Head->next=PLn;
  PL1=PLn;//PLn成爲下一個結點的next指針的指向目標
  PLn=Tmp;//PLn變成需要插入的結點的指針了
 }
 
}


void ShowList(LList *Head)
{
     LList *PL;
     PL=Head->next;
  printf("List is: ");

  while(PL)
  {
         printf("%d  ",PL->elem.num);
         PL=PL->next;
  }
   printf("\n");
}

void main()
{
     int num;
     LList *Head;
     Head=CreatList(4);/*構建4個數據的鏈表*/
  ShowList(Head);

  printf("Reverse the LinkList:\n");
  Reverse(Head);
     ShowList(Head);

     getch();
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章