Question
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
My Answer
void deleteNode(struct ListNode* node){
if(node != NULL){
struct ListNode* temp = node->next;
node->val = temp->val;
node->next = temp->next;
free(temp); //release the memory space
}
}
The complete code
#include <stdio.h>
#include <stdlib.h>
//definition for the singly-linked list.
struct ListNode{
int val;
struct ListNode *next;
};
void build(struct ListNode* head, int* nums, int numsSize){
struct ListNode *p, *q;
p = head;
for(int i=0; i<numsSize; ++i){
q = (struct ListNode*)malloc(sizeof(struct ListNode));
q->next = NULL;
q->val = nums[i];
p->next = q;
p = q;
}
}
void print(const struct ListNode* head){
struct ListNode* p = head->next;
while(p != NULL){
printf("%d ", p->val);
p = p->next;
}
}
void deleteNode(struct ListNode* node){
if(node != NULL){
struct ListNode* temp = node->next;
node->val = temp->val;
node->next = temp->next;
free(temp); //release the memory space
}
}
int main()
{
struct ListNode* L = (struct ListNode*)malloc(sizeof(struct ListNode));
L->next = NULL;
L->val = -1;
int A[] = {1,2,3,4,5,6};
build(L, A, 6);
deleteNode(L);
print(L);
return 0;
}