ZBLOG

我需要你用c语言帮我解决以下问题,首先创建一个链表,此链表的数据由用户自己输入,给你一个链表的头结点head和一个整数val,val由用户自己输入请你删除链表中所有满足Node.val==val的节点,并返回新的头结点。

好的,以下是一个使用C语言解决该问题的示例代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 定义链表节点结构体
  4. struct ListNode {
  5. int val;
  6. struct ListNode* next;
  7. };
  8. // 创建链表节点
  9. struct ListNode* createNode(int value) {
  10. struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
  11. newNode->val = value;
  12. newNode->next = NULL;
  13. return newNode;
  14. }
  15. // 删除指定值的节点
  16. struct ListNode* deleteNodes(struct ListNode* head, int val) {
  17. while (head != NULL && head->val == val) {
  18. struct ListNode* temp = head;
  19. head = head->next;
  20. free(temp);
  21. }
  22. if (head == NULL) {
  23. return NULL;
  24. }
  25. struct ListNode* current = head;
  26. while (current->next != NULL) {
  27. if (current->next->val == val) {
  28. struct ListNode* temp = current->next;
  29. current->next = current->next->next;
  30. free(temp);
  31. } else {
  32. current = current->next;
  33. }
  34. }
  35. return head;
  36. }
  37. // 打印链表
  38. void printList(struct ListNode* head) {
  39. struct ListNode* current = head;
  40. printf("LinkedList: ");
  41. while (current != NULL){
  42. printf("%d ", current -> val);
  43. current = current -> next;
  44. }
  45. printf("\n");
  46. }
  47. int main() {
  48. struct ListNode *head, *newNode, *temp;
  49. int n, i, value, delValue;
  50. // 输入链表数据
  51. printf("请输入链表中的元素个数:");
  52. scanf("%d", &n);
  53. if(n <= 0) {
  54. printf("输入错误!\n");
  55. return 0;
  56. }
  57. head = NULL;
  58. for (i = 0; i < n; i++) {
  59. printf("请输入第 %d 个元素的值:", i+1);
  60. scanf("%d", &value);
  61. newNode = createNode(value);
  62. if (head == NULL) {
  63. head = newNode;
  64. temp = head;
  65. } else {
  66. temp -> next = newNode;
  67. temp = temp -> next;
  68. }
  69. }
  70. // 打印原始链表
  71. printList(head);
  72. // 输入要删除的值
  73. printf("请输入要删除的节点值:");
  74. scanf("%d", &delValue);
  75. // 删除指定节点
  76. head = deleteNodes(head, delValue);
  77. // 打印删除后的链表
  78. printList(head);
  79. return 0;
  80. }

请注意,以上代码是一个简单示例,仅供参考。实际应用中,可能需要根据具体需求进行适当修改和扩展。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10175

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?