题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <iostream> using namespace std; struct Node { int num; Node* next; }; void add(Node* dummy_head, int index_val) { Node* temp = dummy_head; int val = index_val; while (index_val--) { temp = temp->next; } Node* add_node = new Node; add_node->num = val; Node* temp1 = temp->next; temp->next = add_node; add_node->next = temp1; } void print(Node* dummy_head) { Node* temp = new Node; temp = dummy_head->next; while (temp != NULL) { cout << temp->num << " "; temp = temp->next; } } void bulid_link_list(Node* dummy_head, int n) { Node* temp = new Node; temp = dummy_head; for(int i=0;i < n;i++) { Node* cur = new Node; temp->next = cur; cin >> cur->num; temp = temp->next; } temp->next = NULL; } int main() { int n; cin >> n; int index_val; cin >> index_val; Node* dummy_head = new Node; dummy_head->next = NULL; bulid_link_list(dummy_head, n); add(dummy_head, index_val); print(dummy_head); return 0; }