fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node {
  5. int val;
  6. struct node *next;
  7. }Node;
  8.  
  9. Node *head = NULL;
  10.  
  11. Node* createN(int x){
  12. Node *newnode;
  13. newnode = (Node *)malloc(sizeof(Node));
  14. newnode->val = x;
  15. newnode->next = NULL;
  16. return newnode;
  17. }
  18.  
  19. void initL(int n){
  20. int x,i;
  21. Node *p;
  22. scanf("%d",&x);
  23. head = createN(x);
  24. p = head;
  25. for(i=1;i<n;i++){
  26. scanf("%d",&x);
  27. p->next = createN(x);
  28. p = p->next;
  29. }
  30. }
  31.  
  32. void freeL(){
  33. Node *p;
  34. while(head!=NULL){
  35. p = head->next;
  36. free(head);
  37. head = p;
  38. }
  39. }
  40.  
  41. void printL(){
  42. Node *p = head;
  43. while(p != NULL){
  44. printf("%d ",p->val);
  45. p = p->next;
  46. }
  47. printf("\n");
  48. }
  49.  
  50.  
  51. void insMiddle(int n, int x){
  52. int i;
  53. Node *p,*q;
  54. p = head; // 1
  55. for(i=1;i<n;i++){ // 2
  56. p = p->next; // 2
  57. }
  58. q = createN(x); // 3
  59. q->next = p->next; // 4
  60. p->next = q; // 5
  61. }
  62.  
  63. int main(void){
  64. int i,n,y1,x1,y2;
  65. scanf("%d",&n);
  66. initL(n);
  67. printL();
  68. scanf("%d %d",&y1,&x1);
  69. insMiddle(y1,x1);
  70. printL();
  71. freeL();
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0.01s 5268KB
stdin
2
2 4
1 3 
stdout
2 4 
2 3 4