Originally Posted by
Salem
Your first while loop should be something like
Code:
prev = NULL;
while ( node && count < n ) {
prev = node;
node = node->next;
count++;
}
When the loop exits, you have these conditions to deal with.
1. prev may be NULL
2. node may be NULL
3. count may be == n
Work out what each of those things means for your list.
code remove fist and last node
Code:
#include<stdio.h>#include<stdlib.h>
struct node{
int Number;
struct node *next;
};
struct node* newNode(int number, struct node *next) {
struct node *new = malloc(sizeof(*new));
new->Number = number;
new->next = next;
return new;
}
void show(struct node *head){
struct node *c;
c = head;
while (c!=NULL){
printf("%d\n",c->Number);
c = c->next;
}
}
struct node* deleteNode(int n, struct node* node)
{
struct node *first1, *n_th_node, *save;
int count = 0;
save = first1 = n_th_node = node;
first1 = NULL;
while ( node && count < n ) {
first1 = node;
node = node->next;
count++;
}
while ( first1->next != NULL )
{
first1 = first1->next;
save = n_th_node;
n_th_node = n_th_node->next;
}
save->next = n_th_node->next;
free(n_th_node);
return node;
}
int main (void ) {
struct node *head = NULL;
head = newNode(10, head);
head = newNode(20, head);
head = newNode(30, head);
head = newNode(40, head);
head = newNode(50, head);
head = newNode(60, head);
show(head);
head = deleteNode(2, head);
printf("new list \n");
show(head);
return 0;
}
60
50
40
30
20
10
new list
40
30
10