数据结构 - C++单链表删除指定元素的问题?
本文介绍了数据结构 - C++单链表删除指定元素的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
template <class T>
bool SingleList<T>::Delsame(T x)
{
Node<T> *head;
if(NULL == head) return head;
Node<T> *p=head;
Node<T> *first=NULL;
while(NULL != p){
if(p->element == x){
Node<T> *del =p;
p=p->link;
if(NULL!= first){
first->link=p;
}else{
head=p;
}
delete del;
} else{
first=p;
p=p->link;
}
}
return head;
}
代码如上,如 1 2 3 2 4 5 2
需要删除所有的2,
希望得到的结果是1 3 4 5
但目前得到的是1 2 3 4 5,
以及存在无法删除只有一个的元素、连续相同元素无法删除的问题,
如何修改可以将所有相同元素都删去呢?
解决方案
这里有几个问题我看得不是很明白,请你仔细检查一下
head
一开始就定义了,但没赋值就进行了 NULL 检查。虽然没赋值head
是个随机地址不会为 NULL,但这里还是一个很明确的逻辑错误first
从词意上来看,表示第一个节点,但你是用来表示上一个节点的,这里改名为last
比较容易理解?同理,当前指针p
建议改名为current
。在 if 条件中,似乎不需要定义一个
del
来指向 p,因为后面都在使用p->next
,把连接改了之后直接delete p
就可以了,然后可以p = head
或者p = first->next
来改变当前指针。Delsame
定义为bool
,但是返回的却是head
其它逻辑暂时没发现啥问题,我觉得可以先把上面的问题分析处理了再来看看效果。
给你个 JavaScript 的算法参考
JavaScript 主要是提供算法思路,学过 C/C++ 的应该看得明白。然后你可以按这个思路来思考 C++ 怎么实现。
注意:
JavaScript 对对象是引用,这个引用类似 C++ 的指针,与 C++ 的引用不同
JavaScript 不需要 delete,所以改成成 C++ 程序之后需要在合适的地方添加 delete。
class SingleList {
constructor() {
this.head = null;
this.tail = null;
}
print(tag) {
let current = this.head;
function* iterate() {
while (current) {
yield current.value;
current = current.next;
}
}
console.log(`${tag}: ${Array.from(iterate())}`);
}
add(...args) {
let current = this.findTail();
args.forEach(v => {
if (current) {
current.next = {
value: v
};
current = current.next;
} else {
this.head = current = {
value: v
};
}
});
}
findTail() {
if (!this.head) {
return null;
}
let current = this.head;
while (current.next) {
current = current.next;
}
return current;
}
remove(v) {
let current = this.head;
let last = null;
while (current) {
if (current.value === v) {
if (last) {
last.next = current.next;
} else {
this.head = current.next;
}
current = current.next;
} else {
last = current;
current = current.next;
}
}
}
}
function main() {
const list = new SingleList();
list.add(1, 2, 3, 2, 4, 5, 2);
list.print("原始值");
list.remove(2);
list.print("删除 2");
list.add(2, 3, 1, 3, 1);
list.print("新增值");
list.remove(1);
list.print("删除 1");
}
main();
不写 C++ 代码一个是为了让你动动脑筋,二个是因为我懒得去配环境
这篇关于数据结构 - C++单链表删除指定元素的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文