思路:根据题目意思,要返回一个新的链表,那么可以建立一个新的头结点表示新的链表,将符合要求的原链表的结点复制到新链表中。
C 代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
// 本题所说的头结点,指的是链表的第一个结点,实为首元结点
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode));
newHead->next = NULL;
struct ListNode* tail = newHead;
while (head) {
if (head->val != val) {
struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode));
new->val = head->val;
new->next = NULL;
tail->next = new;
tail = new;
}
head = head->next;
}
return newHead->next;
}
官方题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
if (head == NULL) {
return head;
}
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}