Linkedlist- Insert at Nth Position - c

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void insertAtFront(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
temp->next = head;
head = temp;
return ;
}
void displayAll()
{
struct Node* temp = head;
while(temp != NULL)
{
printf("%d\t",temp->data);
temp = temp->next;
}
printf("\n");
}
void insertAtNthPostion(int data,int key)
{
int i;
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
struct Node* temp1 = head;
for(i=1;i<key;i++)
temp1 = temp1->next;
temp->next = temp1->next;
temp1=temp;
displayAll();
return;
}
int main()
{
int num, i, data, key;
head= NULL;
printf("\nHow many data u want to insert? ");
scanf("%d", &num);
for(i=0; i < num; i++)
{
printf("\nEnter the data u want to insert:");
scanf("%d", &data);
insertAtFront(data);
}
displayAll();
printf("Enter the data and position u want to insert:\n");
scanf("%d%d", &data, &key);
insertAtNthPostion(data,key);
return 0;
}
I have tried with this implementation but the values are not changing in the and my output appears as below:
Enter the data u want to insert:
5
5 3 2 1 2
Enter the data and position u want to insert:
265498
2
5 3 2 1 2

You needed to set the previous node's ->next to the new node.
You also forgot the curly brackets on your for loop {}.
You are also forgetting to delete the original node, this won't change the result, but it will waste memory..
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void insertAtFront(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
temp->next = head;
head = temp;
return ;
}
void displayAll()
{
struct Node* temp = head;
while(temp != NULL)
{
printf("%d\t",temp->data);
temp = temp->next;
}
printf("\n");
}
void insertAtNthPostion(int data,int key)
{
int i;
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
struct Node* current = head;
struct Node* previous = NULL;
struct Node* temp = NULL;
for(i=1;i<key;i++) {
previous = current;
current = current->next;
}
new_node->next = current->next;
if (previous != NULL)
previous->next = new_node;
else
head = new_node;
free(current); //Release the old node's memory
displayAll();
return;
}
int main()
{
int num, i, data, key;
head= NULL;
printf("\nHow many data u want to insert? ");
scanf("%d", &num);
for(i=0; i < num; i++)
{
printf("\nEnter the data u want to insert:");
scanf("%d", &data);
insertAtFront(data);
}
displayAll();
printf("Enter the data and position u want to insert:\n");
scanf("%d%d", &data, &key);
insertAtNthPostion(data,key);
return 0;
}
Better Solution:
Although a much better solution would be to change the data of the selected node, without creating a new one:
void insertAtNthPostion(int data,int key)
{
struct Node* current = head;
int i;
for(i=1;i<key;i++) {
current = current->next;
}
current->data = data;
displayAll();
}
Results:
The results with either method will give you this:
Enter the data u want to insert:3
3 2 1
Enter the data and position u want to insert:
4
1
4 2 1

Related

Link not pointing to next element while adding

This is a simple program to add elements at the end of the Linklist using C.
void main() {
int i, n, x;
struct Node* Head = NULL;
struct Node* temp1;
printf("Enter the no. of elements:");
scanf("%d",&n);
printf("\nEnter the elements:");
for (i = 0; i < n; i++) {
temp1 = Head;
struct Node* temp = (Node*)malloc(sizeof(struct Node));
scanf("%d", &x);
temp->data = x;
temp->next = NULL;
if (Head != NULL) {
while (temp1 != NULL) // This part is not working properly
temp1 = temp1->next;
temp1->next=temp;
} else {
Head = temp;
}
}
temp1 = Head;
while (temp != NULL) {
printf("temp=%d tempdata=%d \n",temp,temp->data);
temp = temp->next;
}
}
The while part is not linking the new elements with the previous elements.
As #Groo pointed out, temp1 is null at the end of the while loop so you cannot call temp1->next.
So Just replace the line with
while(temp1->next!=NULL)
But you don't have to traverse all the list elements every time you do an insert to the linked list. As the temp1 would be pointing to the last element in every iteration you just have to make it next pointer to point to the newly allocated node. As done in the below code.
#include<stdlib.h>
#include<stdio.h>
struct Node{
int data;
struct Node *next;
};
void main(){
int i,n,x;
struct Node* Head=NULL;
struct Node* temp1;
printf("Enter the no. of elements:");
scanf("%d",&n);
printf("\nEnter the elements:");
for(i=0;i<n;i++){
struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
scanf("%d",&x);
temp->data=x;
temp->next=NULL;
if(Head!=NULL){
temp1->next=temp;
temp1 = temp;
}
else {
Head=temp;
temp1 = Head;
}
}
temp1=Head;
while(temp1!=NULL){
printf("temp=%d tempdata=%d \n",temp1,temp1->data);
temp1=temp1->next;
}
}
Changing
while(temp1!=NULL)
temp1=temp1->next;
to
while(temp1!=NULL && temp1->next != null)
temp1=temp1->next;
should fix this ;)

Reversing The Last 5 Nodes In A Linked List

I want to reverse the last 5 nodes in a linked list as follows:
Input: 2->4->6->8->10->12->14->16->NULL
Output: 2->4->6->16->14->12->10->8->NULL
I have written the following code to perform the above task but my reverse() function is not working.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
int n;
void insert(struct node **headref, int data) {
struct node *new_node;
new_node = malloc(sizeof(struct node));
new_node->data = data;
new_node->next = *headref;
*headref = new_node;
}
struct node* create() {
struct node dummy;
struct node *new_node = &dummy;
dummy.next = NULL;
int i,num;
printf("Enter The Number Of Data: ");
scanf("%d", &n);
for(i = 1; i <= n; i++) {
printf("Enter Data %d: ", i);
scanf("%d", &num);
insert(&(new_node->next), num);
new_node = new_node->next;
}
return dummy.next;
}
void display(struct node *head) {
struct node *current;
for(current = head; current != NULL; current = current->next) {
printf("%d ", current->data);
}
printf("\n");
}
void reverse(struct node *head) {
struct node *current, *next, *prev, *temp;
current = head;
next = current->next;
prev = NULL;
int i;
for(i = 0; i < n-5; i++) {
temp = current;
current = next;
next = next->next;
}
while(current != NULL) {
current->next = prev;
prev = current;
current = next;
next = next->next;
}
temp->next = prev;
}
int main() {
struct node *start = create();
display(start);
reverse(start);
display(start);
}
Is there any error in my logic in the reverse() function? I tried the dry run on paper and it should have worked but it isn't working. Please point out the mistake that I made or even better suggest some alternative code to solve this problem.
The problem is in the line:
next = next->next;
in this part of the code:
while(current != NULL) {
current->next = prev;
prev = current;
current = next;
next = next->next;
}
In the last element, when current becomes the last node current->next is NULL and you try to get next->next->next which gives segmentation fault.
You need to change the above line simply by adding an if statement:
while(current != NULL) {
current->next = prev;
prev = current;
current = next;
if (next!=NULL) next = next->next;
}
I tried with your given input and it works!!

struct undeclared (first use in this function)

I'm very new to programming and I started to learn C. Now I just cant understand why my node structure is not visible to my functions.
I try to get some help on http://www.cprogramming.com/tutorial/c/lesson7.html
but with no luck in using code blocks 13.12
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct ptr * next;
};
struct node* head;
void Insert(int x)
{
struct node *temp;
temp = (node*)malloc(sizeof(struct node));
if(head == NULL)
head = temp;
temp->data = x;
temp->data = x;
temp->next = NULL;
struct node* temp1 = head;
while(temp1-> != NULL;) {
temp1 = temp1->next;
}
temp1->next = temp;
}
void print() {
struct node* temp = head;
while(temp != NULL) {
printf("the data is %d", temp->data);
temp = temp->next;
}
}
int main ()
{
head = NULL;
int a,c;
printf("How many numbers ? : \n");
scanf("%d",&a);
for(i = 0; i<a; i++); {
printf("Enter a number:\n");
scanf("%d",&c);
Insert(c);
print();
}
}
There are quite a few lets go one by one
number 1
struct node {
int data;
struct node *next; // chagnge ptr -> node
};
number 2
struct node *temp;
temp = malloc(sizeof(struct node)); // struct node casting
number 3
while(temp1->next != NULL) { // remove semi colum and put a next
temp1 = temp1->next;
}
number 4
int i; // for while loop
for(i = 0; i<a; i++) {
Now hopefully it compiles well, check runtime errors ( if any )
and yes
return 0; // just before main
you are building an infinite loop with your first element:
temp = (struct node*)malloc(sizeof(struct node));
if(head == NULL)
head = temp;
temp->data = x;
temp->next = NULL;
struct node* temp1 = head;
while(temp1->next != NULL) { // nothing to do
temp1 = temp1->next;
}
temp1->next = temp; //temp is head and temp1 is head, so head->next points to head
you should do something like
if (head == NULL) {
//fill head and leave
} else {
//traverse to the last element and concatenate the new element
}

Creating Linked List and printing the elements?

I want to create a linked list of numbers from 1 to 1000 and print the numbers.
Im using the function createList() to create the list and printList() to print the elements.
But the following code is crashing.
Can anybody please rectify. I'm new to linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void deleteNode()
{
}
void createList()
{
int i;
struct node* temp = (struct node*)malloc(sizeof(struct node));
head = temp;
struct node* temp1 = (struct node*)malloc(sizeof(struct node));
for(i=0;i<10;i++)
{
temp->data = i+1;
temp->link = temp1;
temp1->link = temp++;
temp1++;
}
}
void printList()
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->link;
}
}
int main()
{
head = NULL;
createList();
printList();
return 0;
}
void createList(){
int i, size = 10;
struct node* temp = malloc(sizeof(struct node));
head = temp;
for(i=0;i<size;i++){
temp->data = i+1;
temp->link = i < size - 1 ? malloc(sizeof(struct node)) : NULL;
temp = temp->link;
}
}
void createList(){
int i, size = 10;
struct node* temp = malloc(size*sizeof(struct node));
head = temp;
if(temp){
for(i=0;i<size;i++){
temp->data = i+1;
temp->link = temp + 1;
++temp;
}
temp[-1].link = NULL;
}
}
void createList()
{
int i;
struct node *temp, *loc_head;
loc_head = head;
for(i=0;i<10;i++)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = i+1;
newnode->link = NULL;
if(head == NULL) {
head=newnode;
loc_head = newnode;
}
else {
head->link = newnode;
head = newnode;
}
}
head = loc_head;
}
don't typecast the result of malloc
Given an array of elements, create a linked list from the array (one new node per
element, using the function that adds nodes to the end of a list).

inserting an element in a linked list

Considering a linked list containing five elements.
1,2,3,4,5 a no '7' is to be inserted after two. we will have an head pointing to the first element of the linked list and ptr at the last. while inserting an element before 3 we will loop through the linked list starting from head to last and we will introduce another pointer(prev) to hold the previous pointers address.ptr will point to the current node and if a matching data is found(3) then we have to include the new node between 2 and 3.
We can do it as we have previous pointer.How to do it without using a previous pointer.
EDITED:
#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list* link;
};
struct list *head=NULL;
struct list *tail=NULL;
void createList(int value);
void displayList(struct list* head_node);
void insertNewNode();
int value;
int main()
{
int i;
for(i=0;i<5;i++)
{
printf("\nEnter the data to be added into the list:\n");
scanf("%d",&value);
createList(value);
}
printf("\nCreated Linked list is\n");
//displayList(head);
printf("\nInsert a node\n");
insertNewNode();
displayList(head);
return 0;
}
void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node,*prev=NULL;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr;ptr=ptr->link)
{
if(ptr->data == 3)
{
printf("Found");
new_node->data = val;
prev->link=new_node;
new_node->link = ptr;
}
prev = ptr;
}
}
void createList(int value)
{
struct list *newNode;
newNode = (struct list*)malloc(sizeof(struct list));
//tail = (struct list*)malloc(sizeof(struct list));
newNode->data = value;
if(head == NULL)
{
head = newNode;
}
else
{
tail->link = newNode;
}
tail = newNode;
tail->link = NULL;
}
void displayList(struct list *head_node)
{
struct list *i;
for(i=head;i;i=i->link)
{
printf("%d",i->data);
printf(" ");
}
printf("\n");
}
void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr;ptr=ptr->link)
{
if(ptr->data == 2)
{
printf("Found");
new_node->data = val;
new_node->link = ptr->link;
ptr->link = new_node;
}
}
}
Update:
This is probably what you want:
void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr->link;ptr=ptr->link)
{
if(ptr->link->data == 3)
{
printf("Found");
new_node->data = val;
new_node->link = ptr->link;
ptr->link = new_node;
}
}
}
Here:
if(ptr->link->data == 3)
you simply look ahead to check if next node has value that you need.
Let's call curr the pointer at the current element, next the pointer at the next element, and value the number stored.
Traverse the list until curr.value == 2, now just create a new_node with new_node.value = 7 and set new_node.next = curr.next and curr.next = new_node

Resources