Skip to content

Instantly share code, notes, and snippets.

@jitsceait
Last active November 29, 2015 04:10
Show Gist options
  • Save jitsceait/5830601bd6801c8203d1 to your computer and use it in GitHub Desktop.
Save jitsceait/5830601bd6801c8203d1 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node * createNode(int val){
Node *temp = (Node *)malloc(sizeof(Node));
if(temp){
temp->data = val;
temp->next = NULL;
}
return temp;
}
/* This function inserts node at the head of linked list */
void push(Node **headRef, int data){
Node * newNode = createNode(data);
newNode->next = *headRef;
*headRef = newNode;
}
void printList(Node *head){
while(head){
printf("%d->", head->data);
head = head->next;
}
printf("Null");
}
/*Function deletes a node from linked list given its pointer
It does not work for last node deletion */
void deleteNode(Node *nodeToDelete){
//Wrong input
if(!nodeToDelete) return;
if(!nodeToDelete->next){
printf("Last node cannot be delete with this method");
return;
}
Node *nextNode = nodeToDelete->next;
//Copy value of next node
nodeToDelete->data = nextNode->data;
//Link nodes
nodeToDelete->next = nextNode->next;
//Delete next node
free(nextNode);
return;
}
int main(void) {
Node *head = NULL;
push(&head, 3);
push(&head, 4);
Node * nodeToDelete = head;
push(&head, 5);
push(&head, 6);
push(&head, 7);
printf("\nOriginal list :");
printList(head);
deleteNode(nodeToDelete);
printf("\nList after deletion :");
printList(head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment