题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
//结构体
typedef struct Node
{
int num;
struct Node *next;
}LinkNode;
//创建链表
LinkNode *creat_link(int n){
int i;
LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
LinkNode *tail;
head->next = NULL;
scanf("%d", &head->num);
tail = head;
for (i = 0; i < n-1; ++i)
{
LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
scanf("%d", &p->num);
p->next = NULL;
tail->next = p;
tail = tail->next;
}
return head;
LinkNode *newnode=(LinkNode *)malloc(sizeof(LinkNode));
if(!newnode)return NULL;
newnode->num = value;
newnode->next = NULL;
if(ptr==NULL){
newnode->next=head;
return newnode;
}else{
if(ptr->next==NULL)ptr->next=newnode;
else{
newnode->next=ptr->next;
ptr->next=newnode;
}
}
return head;
}
int main(int argc, char const *argv[])
{
int n,i;
scanf("%d", &n);
int num;
scanf("%d", &num);
LinkNode *head = creat_link(n);
LinkNode *tail,*ptr;
tail = head;
while(i<=num+1){
ptr = tail;
tail = tail->next;
i++;
}
// printf("%d\n", ptr->num);
tail = head;
printf("%d ", tail->num);
tail = tail->next;
}
printf("\n");
return 0;
}
#include <stdlib.h>
//结构体
typedef struct Node
{
int num;
struct Node *next;
}LinkNode;
//创建链表
LinkNode *creat_link(int n){
int i;
LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
LinkNode *tail;
head->next = NULL;
scanf("%d", &head->num);
tail = head;
for (i = 0; i < n-1; ++i)
{
LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
scanf("%d", &p->num);
p->next = NULL;
tail->next = p;
tail = tail->next;
}
return head;
}
//插入链表
LinkNode *insertNode(LinkNode *head,LinkNode *ptr,int value){LinkNode *newnode=(LinkNode *)malloc(sizeof(LinkNode));
if(!newnode)return NULL;
newnode->num = value;
newnode->next = NULL;
if(ptr==NULL){
newnode->next=head;
return newnode;
}else{
if(ptr->next==NULL)ptr->next=newnode;
else{
newnode->next=ptr->next;
ptr->next=newnode;
}
}
return head;
}
int main(int argc, char const *argv[])
{
int n,i;
scanf("%d", &n);
int num;
scanf("%d", &num);
LinkNode *head = creat_link(n);
LinkNode *tail,*ptr;
tail = head;
while(i<=num+1){
ptr = tail;
tail = tail->next;
i++;
}
// printf("%d\n", ptr->num);
tail = head;
head = insertNode(head, ptr, num);
//打印链表
while(tail != NULL){printf("%d ", tail->num);
tail = tail->next;
}
printf("\n");
return 0;
}