【面試算法系列】逆序輸出一個單鏈表
阿新 • • 發佈:2019-02-18
將一個單鏈表的內容逆序輸出,考慮到當一個連結串列的元素列印之前將該元素的前一個元素列印,運用這個思路可以使用遞迴來實現該功能,(不過該方法仍然存在,問題,當連結串列過長會導致棧溢位問題)程式碼如下:
</pre><pre name="code" class="cpp">/* * File: main.c * Author: Kyle * * Created on 2015年9月7日, 下午2:34 */ #include <stdio.h> #include <stdlib.h> typedef int Item; //定義資料項型別 /* *單鏈表,結構體 */ typedef struct node { Item item; //資料域 struct node* next; //鏈域 } Node; void Add2Tail(Node** pHead, int value) { //連結串列末尾新增一個元素 Node *p = (Node *) malloc(sizeof (Node)); p->item = value; p->next = NULL; if (*pHead == NULL) { *pHead = p; } else { Node *temp = *pHead; while (temp->next != NULL) { temp = temp->next; } temp->next = p; } } void Reversing_Output_List(Node* list) { //遞迴方法,逆序輸出一個連結串列內容 if (list != NULL) { if (list->next != NULL) { Reversing_Output_List(list->next); } printf("%d,", list->item); } } int main() { /** * 2.面試題5 逆序輸出一個連結串列內容 */ Node *p = NULL; Add2Tail(&p, 4); Add2Tail(&p, 56); Add2Tail(&p, 6); Add2Tail(&p, 7); Add2Tail(&p, 9); Add2Tail(&p, 3); Add2Tail(&p, 1); Add2Tail(&p, 66); Add2Tail(&p, 24); Reversing_Output_List(p); return (EXIT_SUCCESS); }