C說話完成單鏈表逆序與逆序輸入實例。本站提示廣大學習愛好者:(C說話完成單鏈表逆序與逆序輸入實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話完成單鏈表逆序與逆序輸入實例正文
單鏈表的逆序輸入分為兩種情形,一種是只逆序輸入,現實上不逆序;另外一種是把鏈表逆序。本文就分離實例講述一下兩種辦法。詳細以下:
1.逆序輸入
實例代碼以下:
#include<iostream> #include<stack> #include<assert.h> using namespace std; typedef struct node{ int data; node * next; }node; //尾部添加 node * add(int n, node * head){ node * t = new node; t->data = n; t->next = NULL; if (head == NULL){ head = t; } else if (head->next == NULL){ head->next = t; } else{ node * p = head->next; while (p->next != NULL){ p = p->next; } p->next = t; } return head; } //次序輸入 void print(node * head){ node * p = head; while (p != NULL){ cout << p->data << " "; p = p->next; } cout << endl; } //遞歸 void reversePrint(node * p){ if (p != NULL){ reversePrint(p->next); cout << p->data << " "; } } //棧 void reversePrint2(node * head){ stack<int> s; while (head != NULL){ s.push(head->data); head = head->next; } while (!s.empty()){ cout << s.top() << " "; s.pop(); } } int main(){ node * head = NULL; for (int i = 1; i <= 5; i++){ head = add(i, head); } print(head); reversePrint(head); reversePrint2(head); system("pause"); return 0; }
逆序輸入可以用三種辦法: 遞歸,棧,逆序後輸入。最初一種接上去講到。
2.單鏈表逆序
實例代碼以下:
#include<iostream> #include<stack> #include<assert.h> using namespace std; typedef struct node{ int data; node * next; }node; node * add(int n, node * head){ node * t = new node; t->data = n; t->next = NULL; if (head == NULL){ head = t; } else if (head->next == NULL){ head->next = t; } else{ node * p = head->next; while (p->next != NULL){ p = p->next; } p->next = t; } return head; } //輪回 node * reverse(node * head){ if (head == NULL || head->next == NULL){ return head; } node * p1 = head; node * p2 = head->next; node * p3 = NULL; head->next = NULL; while (p2 != NULL){ p3 = p2; p2 = p2->next; p3->next = p1; p1 = p3; } head = p1; return head; } void print(node * head){ node * p = head; while (p != NULL){ cout << p->data << " "; p = p->next; } cout << endl; } //遞歸 node * reverse2(node * p){ if (p == NULL || p->next == NULL){ return p; } node * newHead = reverse2(p->next); p->next->next = p; p->next = NULL; return newHead; } int main(){ node * head = NULL; for (int i = 1; i <= 5; i++){ head = add(i, head); } print(head); head = reverse(head); print(head); head = reverse2(head); print(head); system("pause"); return 0; }
這裡鏈表逆序用了兩種辦法:輪回,遞歸。讀者最輕易懂得的辦法就是在紙上本身畫一下。
願望本文所述實例對年夜家的數據構造與算法進修能有所贊助。