如何编写一个C程序来删除单链表中负元素之前的所有节点?
我不熟悉链表。请有人帮我做这个。 我有一个删除节点的程序。我试图在以下原始代码中进行更改。但我面临一些问题如何编写一个C程序来删除单链表中负元素之前的所有节点?,c,linked-list,C,Linked List,我不熟悉链表。请有人帮我做这个。 我有一个删除节点的程序。我试图在以下原始代码中进行更改。但我面临一些问题 #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void push(struct Node** head_ref, int new_data) { struct Node* new_node = (
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void deleteNode(struct Node **head_ref, int key)
{
struct Node* temp = *head_ref, *prev;
if (temp != NULL && temp->data == key)
{
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}
while (temp != NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp); // Free memory
}
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 7);
push(&head, -1);
push(&head, 3);
push(&head, -2);
puts("Created Linked List: ");
printList(head);
deleteNode(&head, 1);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
为了完成工作,我应该在上述计划中做什么更改?
其他节目也受邀参加
#include<stdlib.h>
#include<conio.h>
#include<iostream>
using namespace std;
struct node{
int data;
struct node* link;
};
struct node* head;
void print(struct node* head)
{
struct node* temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<endl;
}
struct node* insert(int x)
{
node*temp= new node;
temp->data=x;
temp->link=NULL;
if(head!=NULL)
{
temp->link=head;
}
head=temp;
return head;
}
struct node* delete_the_node()
{
struct node* temp1=head,*temp2;
while(temp1!=NULL&&temp1->link->data>=0)
{
temp2=temp1;
temp1=temp1->link;
}
if(temp1==head)
{
temp2=temp1->link;
temp1->link=NULL;
}
else{
temp2->link=temp1->link;
temp1->link=NULL;
free(temp1);}
return temp2;
}
int main()
{
cout<<"The linked list is=";
head=NULL;
head=insert(3);
head=insert(-5);
head=insert(7);
head=insert(9);
print(head);
cout<<"The linked list after deletion=";
head=delete_the_node();
print(head);
getch();
return 0;
}
我制作了一个新的程序,它很有效。谢谢大家的支持。我想我不明白,您是想编写新函数还是修改现有函数?我面临一些问题。-像什么?如果有运行时错误,应该在您发布的问题中。如果存在编译时错误,它应该出现在您发布的问题中。如果你期望的结果不是你实际得到的结果,是的,期望的结果和实际的结果都应该出现在你发布的问题中。你在上面所做的尝试,以及它似乎落在地板上的地方,将远比仅仅修改你的代码更有成效。也许会有帮助?对于Yonlif…修改现有的代码