1.題目描述
給定單向鏈表的頭指針和一個要刪除的節點的值,定義一個函數刪除該節點。
返回刪除後的鏈表的頭節點。
注意:此題對比原題有改動
示例 1:
輸入: head = [4,5,1,9], val = 5
輸出: [4,1,9]
解釋: 給定你鏈表中值爲 5 的第二個節點,那麼在調用了你的函數之後,該鏈表應變爲 4 -> 1 -> 9.
示例 2:
輸入: head = [4,5,1,9], val = 1
輸出: [4,5,9]
解釋: 給定你鏈表中值爲 1 的第三個節點,那麼在調用了你的函數之後,該鏈表應變爲 4 -> 5 -> 9.
說明:
題目保證鏈表中節點的值互不相同
若使用 C 或 C++ 語言,你不需要 free 或 delete 被刪除的節點
2.問題分析:
主要是分爲4種情況
1.刪除的結點在頭部
2.刪除的結點在尾部
3.刪除的結點在中間
4.沒有需要刪除的結點
3.代碼實現
3.1C++代碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head == NULL) {
return NULL;
}
if(head->val == val) {//刪除的結點在頭部
return head->next;
}
struct ListNode* pre = head;
while ((pre->next != NULL) && (pre->next->val != val)){
pre = pre->next;
}
if(pre->next != NULL) {
pre->next = pre->next->next;
}
return head;
}
};
3.2Java代碼:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head == null) {
return null;
}
if(head.val == val) {
return head.next;
}
ListNode pre = head;
while ((pre.next != null) && (pre.next.val != val)){
pre = pre.next;
}
if(pre.next != null) {
pre.next = pre.next.next;
}
return head;
}
}