定义一个单链表的储存结构然后用C语言编写一个算法单链表不带头结点统计单链表中值为X的结点个数
时间: 2024-05-10 19:15:18 浏览: 9
单链表的储存结构可以定义如下:
```c
typedef struct ListNode {
int data;
struct ListNode *next;
} ListNode;
```
其中,`data`表示节点储存的数据,`next`表示下一个节点的指针。
下面是单链表不带头结点统计单链表中值为X的结点个数的算法实现:
```c
int count(ListNode *head, int x) {
int cnt = 0;
ListNode *p = head;
while (p != NULL) {
if (p->data == x) {
cnt++;
}
p = p->next;
}
return cnt;
}
```
其中,`head`为单链表的头指针,`x`为要统计的节点的值。使用一个计数器 `cnt`,遍历整个链表,如果节点的值等于 `x`,则 `cnt` 加 1。最后返回 `cnt` 即可。
相关问题
对给定的单链表 L ,设计一个算法,删除 L 中值为 x 的结点的直接前驱结点。C语言
struct ListNode {
int val;
struct ListNode *next;
};
void deletePreNode(struct ListNode *head, int x) {
struct ListNode *p = head;
while (p->next != NULL) {
if (p->next->val == x) {
struct ListNode *pre = p->next;
p->next = pre->next;
free(pre);
return;
}
p = p->next;
}
}
对给定的单链表 L ,设计一个算法,删除 L 中值为 x 的结点的直接前驱结点的c语言代码
以下是删除 L 中值为 x 的结点的直接前驱结点的 C 语言代码:
```c
struct ListNode* deletePredecessor(struct ListNode* head, int x) {
struct ListNode* curr = head;
struct ListNode* prev = NULL;
while (curr != NULL) {
if (curr->next != NULL && curr->next->val == x) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
break;
}
prev = curr;
curr = curr->next;
}
return head;
}
```