單向鏈表的反轉最簡單方法

給出一個單向鏈表的header,要求經過處理變成反向,即原鏈表尾變爲鏈表頭,原鏈表頭變成鏈表尾。

例如:           10->20->30->NULL  

處理後變爲:   30->20->10->NULL

 

我想,下面這應該是時間和空間方面都最簡單的方法。

struct list{
 int value;
 struct list* next;
};

static int reverse(struct list **pl)
{
 struct list* header,*tmp;

 if(*pl==NULL) return 0;

 header = NULL;
 //add node to header and point to next node.
 while(*pl!=NULL) {tmp=*pl; *pl=(*pl)->next; tmp->next=header; header=tmp;}

 *pl = header;
 return 1;
}

 

測試:

static void print_list(struct list *pl)
{
 struct list *header = pl;
 printf("list:");
 while(header!=NULL){
  printf(" %d",header->value);
  header = header->next;
 }
 printf("/n");
}

int _tmain(int argc, _TCHAR* argv[])
{
#define NUMBER  9
 int i = 0;
 int score[NUMBER] = {10,20,30,40,50,60,70,80,90};
 struct list *header,*cur,*tmp;
 
 header = cur = NULL;
 //create list.
 while(i < NUMBER) {
  tmp = (struct list *)malloc(sizeof(struct list));
  tmp->value = score[i];
  tmp->next = NULL;
  if(i==0)
   header = cur = tmp;
  else{
   cur->next = tmp;
   cur = cur->next;
  }
  i++;
 }
 print_list(header);

 reverse(&header);
 print_list(header);

 reverse(&header);
 print_list(header);

 printf("hello,world!/n");
 getch();
 return 0;
}

 

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