我正在尝试从列表中删除节点。我必须使用我用来从列表中删除第一个节点的函数,然后必须添加其他节点(在我想要删除的节点之前)。函数删除列表开头的节点并添加到列表的开头。
我试过这段代码:
List* Delete_theNode(int the_node){
List *temp;
if(head->next == NULL)
{
printf("empty list..");
}
else
{
for(temp = head; temp!= NULL; temp = temp-> next)
{
Delete_node();
}
if(temp->number == the_node)
{
Delete_Node();
}
else
{
printf("\n%d there is no such a node\n", the_node);
}
}
} 发布于 2015-11-15 20:32:09
你的代码中有很多bug!
这种结构更像是一个链表,而不是一个堆栈。
您需要知道前一个节点,以便删除该节点并将列表再次链接到下一个节点。
此外,在删除节点之前,您可能需要释放已删除节点上的内存。
理想情况下:
Stack* Delete_theNode(int the_node) {
//check if it is on the head
if (the_node==head->number) {
Stack * temp = head;
head = head->next;
free(temp);
return;
}
Stack* cur = head->next;
Stack* prev = head;
//while cur is not NULL and prev is not NULL, this is also legit
while (!cur && !prev) {
if (the_node == cur->number) {
Stack *tmp = cur;//the deleted node
prev->next = cur->next;
free(tmp);
return;
}
prev = cur;
cur = cur->next;
}
}发布于 2015-11-15 22:18:02
使用递归重新添加已删除的节点。我试图修复,但没有编译,所以可能有一些语法错误。请验证
Stack* Delete_theNode(int the_node){
if(head == NULL)
{
printf("empty stack..");
}
else
{
if((head != NULL) && (head->number != the_node))
{
Stack *deletedNode = Delete_Node();//Delete top node & reset the head
Delete_theNode(the_node); //Recursive Call
Add_toStack(deletedNode); //Add node and reset the head
}
else if(head->number == the_node)
{
Delete_Node();
}
else
{
printf("\n%d there is no such a node\n", the_node);
}
}
} 发布于 2017-04-24 01:57:57
我使用struct做到了这一点。希望能对你有所帮助。
#include<iostream>
using namespace std;
struct node
{
int number;
node *next;
};
node a, b, c, d, e, *head, *current, *old, myNewNode;//global
bool flag, token;//global
int deletionInt, searchInt, newInt;//global
void Deletion ()
{
cout << "Enter the integer to be deleted: " ;
cin >> deletionInt;
old = head;
current = head;
while(1)
{
if(head==NULL)
{
cout << "Your list is empty, nothing to delete here!" << endl;
break;
}
if(deletionInt==current->number)
{
if(current == head)
{
head= current->next;
current = head;
}
else
{
old->next= current->next;
current = old;
}
break;
}
if(current->next==NULL) break;
else
{
old = current;
current = current->next;
}
}
}https://stackoverflow.com/questions/33719586
复制相似问题