题解 | #牛牛的单向链表#
牛牛的单向链表
https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x), next(NULL) {}
};
ListNode* creatlist(int* arr, int n) {
ListNode* dummyhead = new ListNode(0); //创建哑结点
ListNode* p = dummyhead;
for (int i = 0; i < n; i++) {
p->next = new ListNode(*(arr + i));
p = p->next;
}
return dummyhead->next;
}
void printLinkedNode( const ListNode*
head) { //const在*的左边,左定值确保指针指向的值不会被更改
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
}
int main() {
int n;
cin >> n;
int* arr = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
cin >> *(arr + i);
}
ListNode* p = creatlist(arr, n);
printLinkedNode(p);
}
本程序实现了将数组转化为链表的功能。创建链表的过程中,dummyhead为"哑结点”,这样即便链表初始状态为空,也可以通过哑结点访问,避免了分类讨论。同时使用struct中的构造函数,使得程序更加简化。
#题解##日常学习打卡#