还记得创建单链表的这些代码还是大学时候写过,现在再重新写一写,为面试做准备吧:
创建单链表的两种形式:头插法和尾插法
// 演示创建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; }