單鏈表的逆置 C 實現

2021-06-18 10:04:58 字數 2040 閱讀 3371

對於單鏈表的逆置有兩種方法可以實現:

(1)利用輔助指標

基本思想:在遍歷結點過程中,設定輔助指標,用於記錄先前遍歷的結點。這樣依次編譯的過程中只需修改其後繼結點的next域即可。

實現**:

[cpp]view plain

copy

print?

typedef

intdatatype; 

//型別定義

typedef

struct

nodelinkednode,*linklist;  

void

reverselist(linklist& listhead)  

listhead->next=null;  

listhead=ppre;        //記錄下新的頭結點

}  

示意圖:

(2)遞迴

基本思想:在對當前結點逆置時,先遞迴地逆置其後繼結點,然後將後繼結點指向當前結點。

實現**:

寫了兩個版本

i、返回值為空

[cpp]view plain

copy

print?

void

reverselist(linkednode* pcur,linklist& listhead)  

else

}  

ii、返回值為結點型別

[cpp]view plain

copy

print?

linkednode* reverselist(linkednode* pcur,linklist& listhead)  

else

}  

示意圖:

下面給出完整的程式:

[cpp]view plain

copy

print?

#include

using

namespace

std;  

const

intn=6;  

typedef

intdatatype;

//型別定義

typedef

struct

nodelinkednode,*linklist;  

/****由陣列建立單鏈表****/

linklist createlist(datatype a[n])  

return

listhead;  

}  /****輸出單鏈表****/

void

printlist(linklist listhead)  

cout

}  void

reverselist(linkednode* pcur,linklist& listhead)  

else

}  intmain()  

;   

linkednode* list=createlist(a);  

printlist(list);  

linkednode*ptemp=list;  

reverselist(ptemp,list);  

printlist(list);  

return

0;  

}  

單鏈表逆置實現(C )

對於單鏈表的逆置有兩種方法可以實現 1 利用輔助指標實現 基本思想 在遍歷結點的過程中,設定輔助指標,用於記錄先前遍歷的結點。這樣依次遍歷的過程中只需修改其後繼結點的next域即可。實現 如下 typedef int datatype 型別定義 typedef struct nodelinkedno...

單鏈表的逆置 C 實現

對於單鏈表的逆置有兩種方法可以實現 1 利用輔助指標 基本思想 在遍歷結點過程中,設定輔助指標,用於記錄先前遍歷的結點。這樣依次編譯的過程中只需修改其後繼結點的next域即可。實現 cpp view plain copy print typedef int datatype 型別定義 typedef...

單鏈表的逆置 C 實現

文章出自 對於單鏈表的逆置有兩種方法可以實現 1 利用輔助指標 基本思想 在遍歷結點過程中,設定輔助指標,用於記錄先前遍歷的結點。這樣依次編譯的過程中只需修改其後繼結點的next域即可。實現 cpp view plain copy print?typedef intdatatype 型別定義 typ...