在带头结点 head 的单链表的结点 a 之后插入新元素 x ,试完成下列程序填空。 struct node { elemtype data ; node * next ; B ; yoid lkinsert ( node * head , elemtype x ){ node * S ,* P ; S =_ S -> data = p = head -> next ; while ( p != NULL )&&( p -> data != a ) if ( p == NULL ) cout <<"不存在结点 a !"; else {
时间: 2023-04-09 16:02:49 浏览: 88
B应该填写:head->next = S;
完整程序如下:
struct node {
elemtype data;
node *next;
};
void lkinsert(node *head, elemtype x) {
node *S, *P;
S = new node;
S->data = x;
P = head->next;
head->next = S;
S->next = P;
}
相关问题
在带头结点的单链表表尾处插入一个新元素代码
假设我们已经定义了单链表的结构体和节点结构体,其中头结点为`head`。以下是在带头结点的单链表表尾处插入一个新元素的代码:
```c
// 定义节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 定义单链表结构体
typedef struct LinkedList {
Node* head;
} LinkedList;
// 在表尾插入新元素
void insertAtTail(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->data = data; // 设置新节点的值
newNode->next = NULL; // 新节点的 next 指针指向 NULL
Node* current = list->head;
while (current->next != NULL) { // 找到链表的最后一个节点
current = current->next;
}
current->next = newNode; // 将新节点插入到链表的尾部
}
```
该函数首先创建一个新节点,然后遍历链表,找到链表的最后一个节点,最后将新节点插入到链表的尾部。
在带头结点单链表中查找第i个结点,完成函数 node *find(node *head, int i)的功能。
好的,这是一个比较简单的链表问题。以下是代码实现:
```c++
typedef struct node{
int data;
struct node *next;
}node;
node *find(node *head, int i){
if(head == NULL || i <= 0) // 非法输入
return NULL;
node *p = head->next; // 从第一个结点开始
int j = 1;
while(p != NULL && j < i){ // 遍历链表
p = p->next;
j++;
}
if(j == i) // 找到第i个结点
return p;
else // 链表中没有第i个结点
return NULL;
}
```
函数的参数是一个带头结点的链表头指针和要查找的结点位置i。首先需要判断输入的参数是否合法,即链表是否为空或者i是否小于等于0,如果是则直接返回NULL。接着从第一个结点开始遍历链表,每遍历一个结点就将计数器j加1,直到找到第i个结点或者遍历到链表末尾。如果找到了第i个结点,则返回该结点的指针,否则返回NULL。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)