I want to add newnode behind headnode or others node but node not add whay Should i do?
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node *head, *tail, *behind, *prev,*twonext;
Node *new_node(int val){
struct node *ptr = malloc(sizeof(*ptr));
if(ptr==NULL){
perror("malloc:");
printf("\nFailed to create a new node.\n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
return ptr;
}
Node *creatFirstNode(int val){
return head = tail = new_node(val);
}
void printList(void){
Node *np = head;
printf("\n----Value in Liked list----\n");
while(np){
printf("[%d], ", np->val);
np = np->next;
}
// printf("NULL\n");
}
void freeList(void){
while(head){
Node *np = head->next;
free(head);
head = np;
}
tail = NULL;
}
int main(void){
char cmd =' ';
int k;
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do {
int v = 0;
int s = 0;
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value or 'p'rint or 'q'uit:");
scanf(" %c", &cmd);
fflush(stdin);
switch(cmd){
add headnode--------------------------------------------------------------------
case 'h':
printf("Enter value node head:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
Node *np = new_node(v);
np->next = head;
head = np;
}
fflush(stdin);
printList();
break;
add tail node --------------------------------------------------------------------
case 't':
printf("Enter value node tail:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
tail = tail->next = new_node(v);
}
fflush(stdin);
printList();
break;
add behind node I have problem here What Should i do?? -----------------------------------------------
case 'b':
printf("Enter node value:");
scanf("%d",&v);
Node *np = new_node(v);
printf("Adding value [%d] in new node:",v);
// behind = behind->next = new_node(v);
if(head == NULL)
{
printf("No node to insert behind:");
}
else
{
printf("\nAdd new node behind the value:");
scanf("%d", &s);
np = head;
while(np->val != s);
{
prev=np;
np =np->next;
}
twonext=np->next;
np->next=NULL;
np->next=twonext;
}
fflush(stdin);
printList();
break;
/*case 'p':
printList();
break;
*/
case 'q':
freeList();
printf("\nBye!\n");
getch();
break;
default:
printf("\n Invalid Input ");
}
}while(cmd != 'q' );
return 0;
}
Basically if you want to put a new node between others you've to link the prev->next with the new one and the new->next with the next node. That's all, here is a code example.
case 'b':
printf("Enter node value:");
scanf("%d",&v);
Node *np = new_node(v);
printf("Adding value [%d] in new node:",v);
// behind = behind->next = new_node(v);
if(head == NULL)
{
printf("No node to insert behind:");
}
else
{
printf("\nAdd new node behind the value:");
scanf("%d", &s);
Node *tmp = head; /*You need a tmp variable to go through the list*/
while(tmp->val != s && tmp != NULL);
{
prev=tmp; /*Save the prev node*/
tmp =tmp->next; /*Go through*/
}
if(tmp != NULL){
prev->next = np; /*Link the prev with the new*/
np->next = tmp; /*Link the new one with the subsequent*/
}
}
fflush(stdin);
printList();
break;
Related
Below is my code:
#include <stdio.h>
#include <stdlib.h>
int main() {
struct node {
int data;
struct node *next;
};
int choice;
struct node *head, *newnode, *temp;
head = 0;
while (choice) {
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter items ");
scanf("%d", &newnode->data);
newnode->next = 0;
if (head == 0) {
head = temp = newnode;
} else
temp->next = newnode; /** **this is the problem** **/
temp = newnode; /** temp=newnode works but temp=temp->next doesn't**/
printf("do you want to continue");
scanf("%d", &choice);
}
temp = head;
while (temp != 0) {
printf("list is %d \n", temp->data);
temp = temp->next;
}
}
The problem is here:
if(head==0)
{
head=temp=newnode;
}
else
temp->next=newnode; /** **this is the problem** **/
temp=newnode; /** temp=newnode works but temp=temp->next doesn't**/
Indentation does not determine structure. You must enclose multiple instructions in a block to group them in the else clause. As coded, temp=newnode; is executed unconditionally after the test, which is not a problem, but redundant with head=temp=newnode.
Note also that choice is uninitialized when tested the first time.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int main() {
struct node {
int data;
struct node *next;
};
int choice;
struct node *head, *tail, *newnode, *temp;
head = tail = NULL;
for (;;) {
newnode = (struct node *)malloc(sizeof(struct node));
if (newnode == NULL)
break;
printf("enter item: ");
if (scanf("%d", &newnode->data) != 1) {
free(nownode);
break;
}
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
tail->next = newnode;
}
tail = newnode;
printf("do you want to continue? [0/1] ");
if (scanf("%d", &choice) != 1 || choice == 0)
break;
}
for (temp = head; temp != NULL; temp = temp->next) {
printf("list is %d \n", temp->data);
}
return NULL;
}
I coded a basic linked list working by pointers. It has functions for creating, inserting, deleting, and finding nodes according to positions.
For some reason, the build output says
1>Done building project "Linked List.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
There are no errors unfortunately, so I don't understand what's the problem.
Does anyone see what I'm missing here?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
struct node *head = NULL;
void PrintList()
{
struct node *temp = (node*)malloc(sizeof(node));
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
node* New(int data)
{
node *new = (node*)malloc(sizeof(node));
if (new == NULL)
{
printf("Error \n");
exit(0);
}
new->data = data;
new->next = NULL;
return new;
}
void Create(int data)
{
node *temp = head;
while (temp->next != NULL)
temp = temp->next;
node *new = New(data);
temp->next = new;
}
void Insert(int data, int position)
{
struct node *temp1 = (struct node*)malloc(sizeof(struct node*));
temp1->data = data;
temp1->next = NULL;
if (position == 0)
{
temp1->next = head;
head = temp1;
return;
}
struct node *temp2 = (struct node*)malloc(sizeof(struct node*));
for (int i = 0; i < position - 2; i++)
{
temp2 = temp2->next;
temp2->next = temp1;
}
}
void Delete(int position)
{
struct node *temp1 = (struct node*)malloc(sizeof(struct node*));
if (position == 0)
{
head = temp1->next;
free(temp1);
return;
}
for (int i = 0; i < position - 2; i++)
temp1 = temp1->next;
struct node *temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
int Find(int position)
{
struct node *temp = (node*)malloc(sizeof(node));
for (int i = 0; i < position + 1; i++)
temp = temp->next;
return temp->data;
free(temp);
}
void menu()
{
printf("Linked List in C \n\n");
printf("1.Create an element\n");
printf("2.Insert as the kth element\n");
printf("3.Delete the kth element\n");
printf("4.Find the kth element\n");
printf("0.Exit\n");
}
int main()
{
int command;
int data;
int position;
head = NULL;
menu();
while (1)
{
printf("\nEnter a command (0~4):");
scanf("%d", &command);
if (command == 0)
break;
switch (command)
{
case 1:
printf("Enter a number to be created as the last element: \n");
scanf("%d", data);
Create(data);
PrintList();
break;
case 2:
printf("Enter a number to insert into the list: \n");
scanf("%d", data);
printf("Enter the position to insert this element: \n");
scanf("%d", position);
Insert(data, position);
PrintList();
break;
case 3:
printf("Enter the position of the element to be deleted: \n");
scanf("%d", position);
Delete(position);
PrintList();
break;
case 4:
printf("Enter the position of the element you are looking for: \n");
scanf("%d", position);
int X = Find(position);
printf("The element in node %d is %d. \n", position, X);
PrintList();
break;
}
}
//dispose(head);
return 0;
}
when i created the third node it made the infinity loop of that node. what should i do?
and please insert the code in case 'b' for insert node behind some node.
part1-----------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
char p,j ;
int v;
struct node{
int val;
struct node *next;
};
struct node *head=NULL;
struct node *curr=NULL;
struct node *temp=NULL;
struct node *prev=NULL;
struct node *tail=NULL;
struct node *after=NULL;
part2-----------------------------------------------------------------------------------------------------------------------------
struct node *creatFirstNode(int val){
printf("\ncreating list with headnode as [%d]\n",val);
struct node *ptr=(struct node *)malloc(sizeof(struct node));
if(ptr==NULL){
printf("\nCreated Failed \n");
return NULL;
}
ptr->val=val;
ptr->next=NULL;
head=ptr;
curr=ptr;
return ptr;
}
part3-----------------------------------------------------------------------------------------------------------------------------
main(){
int n,i;
struct node *A=(struct node *)malloc(sizeof(struct node));
struct node *B=(struct node *)malloc(sizeof(struct node));
struct node *C=(struct node *)malloc(sizeof(struct node));
struct node *new=(struct node *)malloc(sizeof(struct node));
struct node *addEnd=(struct node *)malloc(sizeof(struct node));
struct node *addAmong=(struct node *)malloc(sizeof(struct node));
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do{
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value:");
scanf("%c",&p);
fflush(stdin);
part4-----------------------------------------------------------------------------------------------------------------------------
switch(p)
{
case 'h':
printf("Enter value node:");
scanf("%d",&v);
fflush(stdin);
if(head == NULL)
{
creatFirstNode(v);
fflush(stdin);
}
else
{
curr=head;
new->val=v;
new->next=NULL;
curr=new;
curr->next=head;
curr=curr->next;
("\ncreating list with headnode as [%d]\n",v);
head=new;
fflush(stdin);
}
//void printList();
curr=head;
printf("\n----Value in Liked list----\n");
while(curr!=NULL){
printf("[%d], ",curr->val);
curr=curr->next; //change current node
}
break;
part5-----------------------------------------------------------------------------------------------------------------------------
case 't':
printf("Enter value node tail:");
scanf("%d",&v);
curr=head;
while(curr!=NULL){ //Seek for last node
tail=curr;
curr=curr->next; // shift to next node
}
addEnd->val=v;
addEnd->next=NULL;
tail->next=addEnd;
tail=new;
fflush(stdin);
//void printList();.
curr=head;
printf("\n----Value in Liked list----\n");
while(curr!=NULL){
printf("[%d], ",curr->val);
curr=curr->next; //change current node
}
break;
part6-----------------------------------------------------------------------------------------------------------------------------
case 'b':
printf("Enter value node behind:");
scanf("%d",&v);
fflush(stdin);
printf("Adding value [%d] in new node:",&v);
printf("Add new node behind the value:");
void printList();
break;
default:
printf("\n Invalid Input ");
getch();
}
}while(p != 'h' || p != 't' || p != 'b' );
getch();
return 0;
}
example
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node *head, *tail;
Node *new_node(int val){
struct node *ptr = malloc(sizeof(*ptr));
if(ptr==NULL){
perror("malloc:");
printf("\nFailed to create a new node.\n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
return ptr;
}
Node *creatFirstNode(int val){
return head = tail = new_node(val);
}
void printList(void){
Node *np = head;
printf("\n----Value in Liked list----\n");
while(np){
printf("[%d], ", np->val);
np = np->next;
}
printf("NULL\n");
}
void freeList(void){
while(head){
Node *np = head->next;
free(head);
head = np;
}
tail = NULL;
}
int main(void){
char cmd =' ';
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do {
int v = 0;
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value or 'p'rint or 'q'uit:");
scanf(" %c", &cmd);
switch(cmd){
case 'h':
printf("Enter value node head:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
Node *np = new_node(v);
np->next = head;
head = np;
}
break;
case 't':
printf("Enter value node tail:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
tail = tail->next = new_node(v);
}
break;
case 'b':
printf("Enter value node behind:");
scanf("%d", &v);
printf("\nUnimplemented yet.\n");
break;
case 'p':
printList();
break;
case 'q':
freeList();
printf("\nBye!\n");
break;
default:
printf("\n Invalid Input ");
}
}while(cmd != 'q' );
return 0;
}
This question already has an answer here:
Delete element of linked list by a certain criterion
(1 answer)
Closed 7 years ago.
So the problem I'm running into is deleting a user-inputted string from a linked list full of strings.
I'm still having a few issues in understanding just precisely how linked lists work, so any explanation as to what I am doing wrong would be greatly appreciated!
Also, every other function seems to be working just fine, just having issues with the deleteItem function!
Edit - The problem I'm getting when I run the deleteItem function is just my terminal window crashing after getting hung up for a bit.
Here's my code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char name[50];
struct node *next;
}*head;
void display();
void insert();
void count();
void deleteItem();
int main(){
int choice = 1;
char name[50];
struct node *first;
head = NULL;
while(1){
printf("Menu Options\n");
printf("----------------\n");
printf("Please enter the number of the operation you'd like to do: \n");
printf("----------------\n");
printf("1. Insert\n");
printf("2. Display\n");
printf("3. Count\n");
printf("4. Delete\n");
printf("5. Exit\n");
printf("----------------\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
count();
break;
case 4:
if(head=NULL)
printf("The list is blank");
else
deleteItem();
break;
case 5:
return 0;
default:
printf("invalid option");
}
}
system("pause");
return 0;
}
void insert(){
char nameToInsert[50];
struct node *temp;
temp = head;
if(head == NULL){
head = (struct node *)malloc(sizeof(struct node));
printf("What's the name you wish to insert?\n");
scanf("%s", &nameToInsert);
strcpy(head->name, nameToInsert);
head->next = NULL;
}
else{
while(temp->next !=NULL){
temp = temp->next;
}
temp->next = malloc(sizeof(struct node));
temp = temp->next;
printf("What's the name you wish to insert?\n");
scanf("%s", &nameToInsert);
strcpy(temp->name, nameToInsert);
temp->next = NULL;
}
}
void display(){
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp = head;
if(temp == NULL)
printf("The list is empty\n");
else{
printf("%s\n", temp->name);
while(temp->next != NULL){
temp = temp->next;
printf("%s\n", temp->name);
}
}
}
void count(){
struct node *temp;
int c =0;
temp = head;
while(temp!=NULL){
temp=temp->next;
c++;
}
printf("\n%d", c);
}
void deleteItem(){
char nameToDelete[50];
struct node *temp, *previous;
temp = head;
printf("What is the name you wish to delete?\n");
scanf("%s", nameToDelete);
while(temp->next != NULL){
temp = temp->next;
if(strcmp(nameToDelete, temp->name)==0){
previous = temp->next;
free(temp);
printf("%s was deleted successfully\n", nameToDelete);
}
}
}
I see the following issues:
You are not dealing with the case where the item to delete is at the head of the list.
The linked list is not restored to a good state after you free the node that contains the item.
You continue to iterate over the list even after you free the node that contains the item.
Here's a version that should work.
void deleteItem(){
char nameToDelete[50];
struct node *temp, *previous;
temp = head;
printf("What is the name you wish to delete?\n");
scanf("%s", nameToDelete);
// First, locate the node that contains the item.
for ( ; temp->next != NULL; temp = temp->next )
{
if(strcmp(nameToDelete, temp->name)==0)
{
break;
}
prev = temp;
}
// Now take care of deleting it.
if ( temp != NULL )
{
if ( temp == head )
{
head = temp->next;
}
else
{
prev->next = temp->next;
}
free(temp);
printf("%s was deleted successfully\n", nameToDelete);
}
}
Wrote this program in C for linked Lists. I am getting an error in insert when trying to insert at the end of the linked list as a segmentation fault. All other cases are working such as inserting initially,inserting in between 2 elements,etc. Spent a lot of time pondering but couldnt figure out?
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void insert();
void display();
void search();
void delete();
struct node{
int val;
struct node *next;
}*head;
int num,count=0;
void main()
{
char dec = 'E';
printf("Welcome to the Linked List C Program!\n");
head = NULL;
while(1){
printf("Make a Choice:\n");
printf("I.Insert\nD.Delete\nS.Search\nd.Display\nE.Exit\n");
scanf(" %c",&dec);
switch(dec){
case 'I':
insert();
break;
case 'D':
delete();
break;
case 'S':
search();
break;
case 'd':
display();
break;
case 'E':
exit(0);
break;
default:
printf("Wrong input Try Again!\n");
}
}
}
void insert(){
printf("Enter the number to insert:");
scanf("%d",&num);
struct node *temp;
struct node *newnode;
struct node *prev;
int c =0;
//temp = (struct node *)malloc(sizeof(struct node));
newnode = (struct node *)malloc(sizeof(struct node));
//prev = (struct node *)malloc(sizeof(struct node));
newnode->val = num;
if(head==NULL)
{
head = newnode;
head->next = NULL;
}
else
{
temp = head;
//searching whether linked list is in start or end
while(temp->val<num && temp !=NULL)
{
printf("Index:%d Value:%d Address:%p",c,temp->val,temp);
prev = temp;
temp = temp->next;
c++;
printf("TEST\n");
}
if(c==0)
{
head = newnode;
head->next = temp;
}
else
{
prev->next=newnode;
newnode->next=temp;
}
}
}
void display()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d",temp->val);
temp = temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
void search()
{
printf("Enter the number tosearch for:\n");
scanf("%d",&num);
struct node *temp;
temp=head;
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
c++;
}
else if(temp == NULL)
{
printf("Not present!");
}
else
c++;
temp =temp->next;
}
}
void delete()
{
struct node *temp;
struct node *prev;
temp = head;
printf("Enter the value to delete:\n");
scanf("%d",&num);
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
printf("Deleting this element");
prev->next=temp->next;
free(temp);
c++;
}
else
c++;
prev = temp;
temp =temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
In your while loop, you're checking one of temp's members before checking that temp is not NULL:
while(temp->val<num && temp !=NULL)
reverse that:
while ((temp != NULL) && (temp->val < num))