創建單鏈表
阿新 • • 發佈:2018-06-25
true 形式 nod space c++基礎 break 單鏈表 eat reat
還記得創建單鏈表的這些代碼還是大學時候寫過,現在再重新寫一寫,為面試做準備吧:
創建單鏈表的兩種形式:頭插法和尾插法
// 演示創建2種單鏈表的方式 // 【C++基礎】單鏈表.cpp #include "stdafx.h" #include <iostream> using namespace std; struct link { int data; link *next; }; //頭插法建立單鏈表 link *creatLink_head(link *head) { link *node; int tmpData; cout << "輸入元素,以空格分隔:"; do { cin >> tmpData; if (tmpData == 0) break; node = new link; node->data = tmpData; node->next = head->next; head->next = node; } while (node->data != 0); return head->next; } //尾插法建立單鏈表 link *creatLink_tail(link *head) { link *node, *tail = head; int tmpData; cout << "輸入元素,以空格分隔:"; do { cin >> tmpData; if (tmpData == 0) break; node = new link; node->data = tmpData; tail->next = node; tail = node; tail->next = NULL; } while (tmpData != 0); return head->next; } //遍歷輸出 void printLink(link *p){ while (p != NULL) { cout << p->data << " "; p = p->next; } cout << endl; } int main() { link *head, *p_head, *p_tail; head = new link; head->next = NULL; //方式1:頭插法創建單鏈表 //p_head = creatLink_head(head); //printLink(p_head); //方式2:尾插法創建單鏈表 p_tail = creatLink_tail(head); printLink(p_tail); return 0; }
創建單鏈表