fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6. int data;
  7. struct node *next;
  8. };
  9.  
  10. typedef struct node NODE;
  11.  
  12. /* 创建单链表 */
  13. NODE *creatlist()
  14. {
  15. NODE *head, *p, *s;
  16. int num;
  17.  
  18. head = (NODE *)malloc(sizeof(NODE));
  19. p = head;
  20.  
  21. printf("1 2 3 4 5 6 0:\n");
  22. scanf("%d", &num);
  23.  
  24. while (num != 0)
  25. {
  26. s = (NODE *)malloc(sizeof(NODE));
  27.  
  28. s->data = num;
  29. p->next = s;
  30. p = s;
  31.  
  32. scanf("%d", &num);
  33. }
  34.  
  35. p->next = NULL;
  36.  
  37. return head;
  38. }
  39.  
  40. /* 删除第3个结点 */
  41. void deleteNode(NODE *head, int i)
  42. {
  43. NODE *p, *s;
  44. int j = 0;
  45.  
  46. p = head;
  47.  
  48. /* 找到待删除结点的前一个结点 */
  49. while (p->next != NULL && j < i - 1)
  50. {
  51. p = p->next;
  52. j++;
  53. }
  54.  
  55. if (p->next == NULL || j != i - 1)
  56. {
  57. printf("删除位置非法!\n");
  58. }
  59. else
  60. {
  61. s = p->next;
  62. p->next = s->next;
  63.  
  64. free(s);
  65. }
  66. }
  67.  
  68. int main()
  69. {
  70. NODE *q, *HEAD;
  71. int i;
  72.  
  73. HEAD = creatlist();
  74.  
  75. printf("1 2 3 4 5 6:\n");
  76.  
  77. q = HEAD->next;
  78.  
  79. while (q != NULL)
  80. {
  81. printf("%d\t", q->data);
  82. q = q->next;
  83. }
  84.  
  85. printf("\n");
  86.  
  87. printf("3");
  88. scanf("%d", &i);
  89.  
  90. deleteNode(HEAD, i);
  91.  
  92. printf("1 2 3 4 5 6:\n");
  93.  
  94. q = HEAD->next;
  95.  
  96. while (q != NULL)
  97. {
  98. printf("%d\t", q->data);
  99. q = q->next;
  100. }
  101.  
  102. printf("\n");
  103.  
  104. return 0;
  105. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
1 2 3 4 5 6 0:
1 2 3 4 5 6:

3删除位置非法!
1 2 3 4 5 6: