(C語言)鏈表的反轉(一次遍歷)

/**

*Node爲節點類型,root保存的是第一個節點的地址

*/


Node * reverse_linklist(Node *root)       //傳入根節點

{

          Node *current;

          Node *pnext;

/*遍歷開始current記錄當前位置,pnext記錄下一位置*/

          current = root;

          pnext = root->next;

/*********判斷鏈表是否爲空*********/

if(root == NULL)


{


            fprintf(stderr,"the link is empty!\n");

            return NULL;

}

current->next = NULL;             /*將第一個節點指針域置爲空*/

/***************實現反轉*********************/

while(pnext != NULL)

{

       root = pnext->next;//跟新root爲pnext的下一節點

      pnext->next  = current;//跟新pnext->爲它的上一節點即current

       current = pnext;          

       pnext = root;

}

root = current;


return root;

}

發佈了4 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章