已知带有头结点的单链表L(不同结点的数据域值可能相同),设计一个算法统计L中数据域为x的结点的个数。(要求写出单链表的存储结构描述)
typedef struct Node {
int data; // 数据域
struct Node * next; // 指针域
} Node, *LinkedList;
int countNodeWithValueX(LinkedList L, int x) {
Node * p = L -> next;
int count = 0;
while (p != NULL) {
if (p -> data == x) {
count++;
}
p = p -> next;
}
return count;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:#include <stdio.h>
#define MAXSIZE 100
typedef char Elemtype;
typedef struct//顺序线性表存储结构
{
Elemtype elem[MAXSIZE];
int last;
}seqlist;
void insert(seqlist *L,Elemtype x)
{
int k;
int i;
for(i=0;i<=L->last;i++)//找出应插入位置i
{
if(L->elem[i]>=x)
break;
}
if(i>L->last)
L->elem[L->last+1]=x;
for(k=L->last;k>=i;k--)
{
L->elem[k+1]=L->elem[k];//移位
}
L->elem[i]=x;//赋值
L->last++;//指针后退
for(k=0;k<=L->last;k++)//打印线性表
{
printf("%d\n",L->elem[k]);
}
}
main()
{
seqlist *L;
int x;
int i;
int r;
printf("请输入线性表的长度:");//给数组赋值
scanf("%d",&r);
L->last = r-1;
for(i=0; i<=L->last; i++)
{
printf("输入数组递增元素");
scanf("%d",&L->elem[i]);
}
printf("输入一个插入的数字");
scanf("%d",&x);
insert(L,x);
}
有错误请指正!
Answer:
Sure, I can help with your problem.
First, let me explain the storage structure for a single linked list. A single linked list consists of nodes, where each node has two parts: a data field and a pointer to the next node. The list is accessed through its head node, which points to the first node in the list. Each node in the list has a data field and a pointer to the next node. The last node in the list points to NULL, indicating that there are no more nodes in the list.
Now, let's look at the algorithm for counting the number of nodes in a single linked list L that have a data field value of x.
int count_nodes(Node* head, int x) {
int count = 0;
Node* current = head;
while (current != NULL) {
if (current->data == x) {
count++;
}
current = current->next;
}
return count;
}
Explanation: 1. We start by initializing a count variable to 0 and a current pointer to the head node of the linked list. 2. We then loop through the linked list using the while loop, continuing as long as the current pointer is not NULL. 3. Inside the loop, we check if the data field of the current node is equal to the value of x. If it is, we increment the count variable by 1. 4. We update the current pointer to point to the next node in the list. 5. After looping through all the nodes in the list, we return the count variable, which now holds the number of nodes with a data field value of x.
I hope this helps! Let me know if you have any other questions.