题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <stdio.h> #include <string.h>
struct NODE_STU{ int val; struct NODE_STU *next; };
void insertNode(struct NODE_STU *head,int insertVal, int nodeVal) { struct NODE_STU *ptr = head; struct NODE_STU *ptr2 = NULL; while(ptr) { if(ptr->val == nodeVal) { ptr2 = ptr->next; ptr->next = (struct NODE_STU *)malloc(sizeof(struct NODE_STU)); ptr->next->next = ptr2; ptr->next->val = insertVal; break; } ptr = ptr->next; } }
void delNode(struct NODE_STU *head,int delVal) { struct NODE_STU *ptr = head; struct NODE_STU *ptr2 = NULL; if(ptr->val == delVal) { head = ptr->next; free(ptr); } else { while(ptr->next) { if(ptr->next->val == delVal) { ptr2 = ptr->next; ptr->next = ptr->next->next; free(ptr2); break; } ptr = ptr->next; } } }
void printNode(struct NODE_STU *head) { struct NODE_STU *ptr = head;
while(ptr)
{
printf("%d ", ptr->val);
ptr = ptr->next;
}
printf("\n");
}
int main(void) { int n = 0; int headVal = 0; int nodeVal = 0; int insertVal = 0; int delVal = 0; struct NODE_STU *head = (struct NODE_STU *)malloc(sizeof(struct NODE_STU));
int i = 0;
while(scanf("%d", &n) != EOF)
{
scanf("%d", &headVal);
head->val = headVal;
head->next = NULL;
for(i = 0; i < n - 1; i++)
{
scanf("%d %d", &insertVal, &nodeVal);
insertNode(head, insertVal, nodeVal);
}
scanf("%d", &delVal);
delNode(head, delVal);
printNode(head);
}
return 0;
}