fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Node {
  5. char data;
  6. struct Node* next;
  7. };
  8.  
  9. struct Node* InitList() {
  10. return NULL;
  11. }
  12.  
  13. struct Node* InsertTail(struct Node* head, char e) {
  14. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  15. newNode->data = e;
  16. newNode->next = NULL;
  17. if (!head) {
  18. return newNode;
  19. }
  20. struct Node* p = head;
  21. while (p->next) {
  22. p = p->next;
  23. }
  24. p->next = newNode;
  25. return head;
  26. }
  27.  
  28. void DispList(struct Node* head) {
  29. struct Node* p = head;
  30. while (p) {
  31. printf("%c", p->data);
  32. p = p->next;
  33. }
  34. printf("\n");
  35. }
  36.  
  37. int ListLength(struct Node* head) {
  38. int len = 0;
  39. struct Node* p = head;
  40. while (p) {
  41. len++;
  42. p = p->next;
  43. }
  44. return len;
  45. }
  46.  
  47. int ListEmpty(struct Node* head) {
  48. return head == NULL;
  49. }
  50.  
  51. int GetElem(struct Node* head, int i, char* e) {
  52. int j = 1;
  53. struct Node* p = head;
  54. while (p && j < i) {
  55. p = p->next;
  56. j++;
  57. }
  58. if (!p || j > i) {
  59. return 0;
  60. }
  61. *e = p->data;
  62. return 1;
  63. }
  64.  
  65. int LocateElem(struct Node* head, char e) {
  66. int i = 1;
  67. struct Node* p = head;
  68. while (p) {
  69. if (p->data == e) {
  70. return i;
  71. }
  72. p = p->next;
  73. i++;
  74. }
  75. return 0;
  76. }
  77.  
  78. int main() {
  79. struct Node* h = InitList();
  80. h = InsertTail(h, 'a');
  81. h = InsertTail(h, 'b');
  82. h = InsertTail(h, 'c');
  83. h = InsertTail(h, 'd');
  84. h = InsertTail(h, 'e');
  85.  
  86. DispList(h);
  87. printf("%d\n", ListLength(h));
  88. printf("%s\n", ListEmpty(h) ? "空" : "非空");
  89.  
  90. char elem;
  91. if (GetElem(h, 3, &elem)) {
  92. printf("%c\n", elem);
  93. }
  94. printf("%d\n", LocateElem(h, 'a'));
  95.  
  96. return 0;
  97. }
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
abcde
5
非空
c
1