ZBLOG

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

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

#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct ListNode {
    int val;
    struct ListNode* next;
};

// 创建链表节点
struct ListNode* createNode(int value) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = value;
    newNode->next = NULL;
    return newNode;
}

// 删除指定值的节点
struct ListNode* deleteNodes(struct ListNode* head, int val) {
    while (head != NULL && head->val == val) {
        struct ListNode* temp = head;
        head = head->next;
        free(temp);
    }
    
    if (head == NULL) {
        return NULL;
    }
    
    struct ListNode* current = head;
    
    while (current->next != NULL) {
        if (current->next->val == val) {
            struct ListNode* temp = current->next;
            current->next = current->next->next;
            free(temp);
        } else {
            current = current->next;
        }
    }
    
    return head;
}

// 打印链表
void printList(struct ListNode* head) {
    struct ListNode* current = head;

    printf("LinkedList: ");
  
  	while (current != NULL){
      	printf("%d ", current -> val);
      	current = current -> next; 
  	}
  
  	printf("\n");
}

int main() {
  	struct ListNode *head, *newNode, *temp;
  	int n, i, value, delValue;

  	// 输入链表数据
  	printf("请输入链表中的元素个数:");
  	scanf("%d", &n);

  	if(n <= 0) {
      	printf("输入错误!\n");
      	return 0;
  	}

  	head = NULL;

  	for (i = 0; i < n; i++) {
      	printf("请输入第 %d 个元素的值:", i+1);
      	scanf("%d", &value);

      	newNode = createNode(value);

      	if (head == NULL) {
          	head = newNode;
          	temp = head;
      	} else {
          	temp -> next = newNode;
          	temp = temp -> next;
     	}
  	}
  
  	// 打印原始链表
  	printList(head);
  
    // 输入要删除的值
    printf("请输入要删除的节点值:");
    scanf("%d", &delValue);
    
    // 删除指定节点
    head = deleteNodes(head, delValue);
    
    // 打印删除后的链表
    printList(head);
    
  	return 0;
}

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?