[LeetCode-203] Remove Linked List Elements(連結串列節點刪除)
阿新 • • 發佈:2019-02-02
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
【分析】頭結點放到最後來刪除,先儲存要刪除節點前面一個節點,然後再刪除。
程式碼如下:
struct ListNode* removeElements(struct ListNode* head, int val)
{
if (!head)
return NULL;
struct ListNode* curTemp = head;/*當前要處理的節點*/
struct ListNode* nextTemp = head->next;
/*1.處理頭結點以外的結點*/
while(nextTemp) {
if(val == nextTemp->val) {
curTemp->next = nextTemp->next;
free(nextTemp);
nextTemp = curTemp->next;
continue;
}
nextTemp = nextTemp->next;
curTemp = curTemp->next;
}
/*2.處理頭結點*/
if(head->val == val) {
curTemp = head;
head = head->next;
free(curTemp);
}
return head;
}