已知带头结点单链表L中存储一组整数,编写算法删除表中所有值大于x的结点。
时间: 2023-05-21 11:02:26 浏览: 67
以下是删除表中所有值大于x的结点的算法:
```
void deleteNodesGreaterThanX(ListNode* head, int x) {
ListNode* current = head->next;
ListNode* previous = head;
while (current != nullptr) {
if (current->val > x) {
previous->next = current->next;
delete current;
current = previous->next;
} else {
previous = current;
current = current->next;
}
}
}
```
其中,ListNode 是单链表的结点类型,head 是头结点,val 是结点存储的整数值。
相关问题
已知带头结点的动态单链表l中的结点是按整数值递增排列的,试写一算法将值x为的结点插入到表l 中,使l仍然有序。
题目中告诉我们,单链表L中的结点按整数值递增排列,我们需要编写一个算法,将值x的结点插入到表L中的适当位置。
我们可以沿着链表移动,找到第一个大于等于x的结点和它的前驱结点。然后用新结点替换它的前驱结点的后继指针,把它作为新结点的后继指针,这样就将新结点插入到链表中了。
具体的实现可以参考如下代码:
```
typedef struct Node *PtrToNode;
struct Node {
int data;
PtrToNode next;
};
typedef PtrToNode List;
typedef PtrToNode Position;
void Insert(List L, int x) {
Position p, tmp;
p = L->next;
while (p != NULL && p->data < x) {
tmp = p;
p = p->next;
}
tmp->next = malloc(sizeof(struct Node));
tmp->next->data = x;
tmp->next->next = p;
}
```
在函数内部,我们首先将指针p指向表头的后继结点,然后沿着链表移动,直到找到第一个大于等于insertVal的结点和它的前驱结点tmp。然后我们使用malloc函数为新结点分配内存空间,更新tmp的后继指针,将新结点插入到链表中,最后返回链表的头指针L。
已知带头结点的单链表L中的结点是按照整数值递增排列的,写一个算法,将值为X的结点插入到表L中,使得L仍然递增有序
可以回答这个问题。算法如下:
1. 新建一个结点p,将值为X赋给p的数据域。
2. 从头结点开始遍历链表,找到第一个值大于X的结点p1和它的前驱结点p2。
3. 将p插入到p2和p1之间,即p2的next指针指向p,p的next指针指向p1。
4. 如果遍历到链表末尾都没有找到大于X的结点,则将p插入到链表末尾。
代码实现如下:
void insertNode(ListNode* head, int x) {
ListNode* p = new ListNode(x);
ListNode* p1 = head->next;
ListNode* p2 = head;
while (p1 != NULL && p1->val < x) {
p2 = p1;
p1 = p1->next;
}
p2->next = p;
p->next = p1;
}
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)