师--链表的结点插入
Problem Description
給出一個只有頭指針的鏈表和 n 次操作,每次操作為在鏈表的第 m 個元素后面插入一個新元素x。若m 大于鏈表的元素總數則將x放在鏈表的最后。Input
多組輸入。每組數據首先輸入一個整數n(n∈[1,100]),代表有n次操作。 接下來的n行,每行有兩個整數Mi(Mi∈[0,10000]),Xi。Output
對于每組數據。從前到后輸出鏈表的所有元素,兩個元素之間用空格隔開。Example Input
4 1 1 1 2 0 3 100 4Example Output
3 1 2 4
 
 
 
 
 #include <stdio.h>
 #include <stdlib.h>
 struct node
 {
 ? ? int data;
 ? ? struct node *next;
 };
 struct node *create(int n)
 {
 ? ? struct node *head,*p,*tail,*q;
 ? ? int i,x,len,j;
 ? ? head=(struct node*)malloc(sizeof(struct node));
 ? ? head->next=NULL;
 ? ? tail=head;
 ? ? len=0;
 ? ? for(i=0;i<n;i++)
 
 
 ? ? {
 ? ? ? ? p=(struct node*)malloc(sizeof(struct node));
 ? ? ? ? scanf("%d %d",&x,&p->data);
 ? ? ? ? p->next=NULL;
 ? ? ? ? if(x>=len)
 ? ? ? ? {
 ? ? ? ? ? ? tail->next=p;
 ? ? ? ? ? ? tail=p;
 ? ? ? ? ? ? len++;
 ? ? ? ? }
 ? ? ? ? else if(x==0)
 ? ? ? ? {
 ? ? ? ? ? ? p->next=head->next;
 ? ? ? ? ? ? head->next=p;
 ? ? ? ? ? ? len++;
 ? ? ? ? }
 ? ? ? ? else if(x>0&&x<len)
 ? ? ? ? {
 ? ? ? ? ? ? q=head;
 ? ? ? ? ? ? for(j=0;j<x;j++)
 ? ? ? ? ? ? {
 ? ? ? ? ? ? ? ? q=q->next;
 ? ? ? ? ? ? }
 ? ? ? ? ? ? p->next=q->next;
 ? ? ? ? ? ? q->next=p;
 ? ? ? ? ? ? len++;
 ? ? ? ? }
 ? ? }
 ? ? return (head);
 };
 void print(struct node *h)
 {
 ? ? struct node *p=h->next;
 ? ? while(p!=NULL)
 ? ? {
 ? ? ? ? if(p->next==NULL)
 ? ? ? ? ? ? printf("%d",p->data);
 ? ? ? ? else
 ? ? ? ? ? ? printf("%d ",p->data);
 ? ? ? ? p=p->next;
 ? ? }
 }
 int main()
 {
 ? ? int n;
 ? ? while(scanf("%d",&n)!=EOF)
 ? ? {
 ? ? ? ? struct node *p;
 ? ? ? ? p=create(n);
 ? ? ? ? print(p);
 ? ? ? ? printf("\n");
 ? ? }
 ? ? return 0;
 }
 
 
 
 
 
總結
以上是生活随笔為你收集整理的师--链表的结点插入的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 数据结构实验之排序一:一趟快排
- 下一篇: 非线性回归
