實現單鏈表反轉主要思路:
需要注意的是:鍊錶在使用結束後,需要釋放記憶體(如果是new的要delete,malloc的要free)
具體**如下所示(包含遞迴和非遞迴兩種方法):
#pragma once
#ifndef list_h
#define list_h
#include
using namespace std;
struct listnode
; listnode(int value):val(value),next(null){};
};//構造帶頭結點的鍊錶
int initlist(listnode* head)
for (int j=
0;j<
10;j++)
cout
//逆序單鏈表--非遞迴實現
listnode* reverselink(listnode* head)
return preversehead;
}//逆序單鏈表--遞迴實現
listnode* reverselist(listnode* p, listnode*
&head)
else
//0->1->2->3->4->5->6->7->8->9
//程式結束之後0->1,1->0
}//逆序輸出單鏈表元素
int printreverselist(listnode* head)
//注意鍊錶使用結束時要釋放記憶體
int deletelist(listnode* head)
cout
//列印函式
void printnode(listnode* node)
cout<}#endif
// reverselink.cpp : 定義控制台應用程式的入口點。
//#include "stdafx.h"
#include "list.h"
int _tmain(int argc, _tchar* argv)
單鏈表反轉
單鏈表反轉,可以用迴圈做,當然也可以遞迴 詳見 include includestruct node 3 1 4 6 2 1 1 3 4 6 2 2 4 1 3 6 2 3 6 4 1 3 2 4 2 6 4 1 3 5 迴圈反轉,即依次改動3個指標值,直到鍊錶反轉完成 比如,上面第 1 行到第 2...
反轉單鏈表
include stdafx.h include include using namespace std struct listnode typedef listnode plistnode typedef plistnode list list creatlist return head void...
單鏈表反轉
想起很早以前某次面試,面試官很嚴肅的要求我現場手寫單鏈表反轉的 哥虎軀一震,心想 不就需要要個臨時變數來記錄位址嗎,用得著這樣煞有介事?雖然在那之前我的確沒寫過這個程式,哈哈哈 當時我草草寫了十來行 面試官不等我完成,就直接拿過去開始問問題。不知道是不是因為抗壓能力不足,在面試官的不斷 盤問 下,哥...