LeetCode 203. 刪除連結串列中的節點 C++&java
阿新 • • 發佈:2018-12-30
刪除連結串列中等於給定值 val 的所有節點。
示例:
輸入: 1->2->6->3->4->5->6, val = 6 輸出: 1->2->3->4->5C++/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* p = new ListNode(1) ;
p->next = head ;
ListNode* re ;
re = p ;
if(head ==NULL) return NULL ;
while(head)
{
if(head->val == val)
{
p ->next = head->next ;
ListNode* q ;
q = head ;
head = head->next ;
delete q;
q = NULL ;
}
else
{ p = p->next ;
head = head->next ;
}
}
return re->next;
}
};
JAVA :
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode p = new ListNode(1) ; // 用一個節點來存放要檢測的上一個節點
p.next = head ;
ListNode re = p;
if(head == null) return null ;
while(head !=null)
{
if(head.val==val)
{
p.next = head.next;
}
else
{
p = p.next;
}
head = head.next;
}
return re.next;
}
}