題目:
畫圖解析:
方法:雙指針
解答代碼(注:解答代碼帶解析):
//題目給的結構體
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
typedef struct ListNode ListNode;
ListNode* removeElements(struct ListNode* head, int val) {ListNode* newHead, * newTail;newHead = newTail = NULL;ListNode* pcur = head;while (pcur){if (pcur->val != val){if (newHead == NULL)//鏈表的頭結點沒有找到{newHead = newTail = pcur;//找到新的鏈表的頭結點newHead,這個頭結點后面要傳回去,不能動。}else//找到頭結點之后這時候newHead和newTail都在頭結點{newTail->next = pcur;//先存儲pcur的地址newTail = newTail->next;//再走下一步}}pcur = pcur->next;//無論怎么樣pcur都要走下一步,找到要移除的元素直接跳過就行}if (newTail)//這時候pcur=NULL;但是newTail->next沒有改為NULL,鏈表不完整{newTail->next = NULL;}return newHead;
}
建議動手敲一敲!!
上面的代碼是老師教的,下面分享我寫的,我自己寫的代碼時間復雜度太高了,不建議模仿。
本人自己寫的代碼:
#define _CRT_SECURE_NO_WARNINGS 1
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
typedef struct ListNode ListNode;
ListNode* removeElements(struct ListNode* head, int val) {ListNode* newHead, * newTail, * phead;if (head == NULL){return head;}phead = head;while (phead)//找新的頭結點{if (phead->val != val){newHead = phead;//只要不是移除元素,這個結點就是新的頭結點,找到馬上跳出循環break;}phead = phead->next;}if (phead == NULL){return NULL;}newTail = phead = newHead;while (phead){if (phead->val != val){newTail = phead;phead = phead->next;}else{ListNode* del = phead;phead = phead->next;newTail->next = phead;free(del);del = NULL;}}return newHead;
}
完!!