题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
https://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h> #include <malloc.h> typedef struct node { int data; struct node *next; }node; //创建 node *creatnode() { node *head=(node*)malloc(sizeof(node)); if(head==NULL) return NULL; head->next=head; return head; } //尾插 void insertnode(node *head,int data) { node *new=(node*)malloc(sizeof(node)); if(head==NULL) return; new->data=data; new->next=NULL; node *p=NULL; for(p=head;p->next!=head;p=p->next); new->next=p->next; p->next=new; } void addnode(node *head,int i) { int k; for(k=0;k<i;k++) { head=head->next; } node *p=(node*)malloc(sizeof(node)); p->data=i; p->next=head->next; head->next=p; } //打印 void printfnode(node *head) { if(head->next==head) return; node *p=head->next; while(p!=head) { //head=head->next; printf("%d ",p->data); p=p->next; } } int main() { node *head=creatnode(); int n,i; scanf("%d",&n); scanf("%d",&i); int a[n],k,j; for(k=0;k<n;k++) { scanf("%d",&a[k]); } for(j=0;j<n;j++) { insertnode(head, a[j]); } addnode(head, i); printfnode(head); }