这个是在参加面试的时候遇到的题目,说句实话,我当时不懂。
后面查了资料,里面写的比较仔细就不多说了。
#include <iostream>
using namespace std;
struct node {int data;node* next;node(int data, node* next = NULL) {this->data = data;this->next = next;}
};node* createlist() {node* head = NULL;node* cur = NULL;int n;cout << "请输入链表的长度" <<endl ;cin >> n;for (int i = 0; i < n; i++) {//head = new node(i,head);//当i=0时就会创建一个节点,即当head=null时创建节点,head中只有一个参数1,//并且将此时的链表传值给cur//且head也不为null了if (head == NULL) {head = new node(i);cur = head;}//当head不为空时,赋值给cur之后,此时的cur已经有了地址else {cur->next = new node(i);//将此时的节点的地址给到cur的指针域cur = cur->next;}}return head;
}void displaylist(node* head) {cout << "Linkedlist node -> ";while (head != NULL) {cout << head->data << " ";head = head->next;}cout << endl;
}int main() {node* head = createlist();displaylist(head);return 0;
}