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