删除链表中等于给定值 val 的所有元素。
示例
给定: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
返回: 1 --> 2 --> 3 --> 4 --> 5
————————————————————————————————————————————————
/**
* 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 *prior,*p;
//本身空表
if(head==NULL)
return NULL;
while((head!=NULL)&&(head->val==val))
head=head->next;//连串相等,节点后移
//*********************************划重点******************************************
while((head==NULL)||(head->next==NULL))
return head;
//*********************************重点完******************************************
prior=head;
p=head->next;
//开始比较
while(p!=NULL)
{
if(p->val==val)
{
prior->next=p->next;
}
else
{
prior=prior->next;
}
p=p->next;
}
return head;
// while ( head != NULL && head->val == val){
// head = head->next; //将头节点后移
// }
// if ( head == NULL) { //链表为空
// return NULL;
// }
//
// ListNode *pre = head;
// ListNode *p = head->next;
//
// while( p != NULL) {
// if ( p->val == val) {
// pre->next = p->next; //将原节点p删除
// } else {
// pre = p; //向后移动一个节点
// }
// p = p->next;
// }
// return head;
}
};
————————————————————————————————————————————————
打注释的是别人家的代码。
如果没有重点的部分LEETCODE会报错:member access within null pointer of type ‘struct ListNode’
这个问题主要是由于测试系统不知道当前的结点prior(head)与结点的下一个结点p(head->next)是否为NULL,而自己有没有声明,所以系统不确定,于是就报错。这也说明了链表中的结点使用的时候比其他数据结构要严格一些,一定要时刻保证使用的结点不为NULL,为NULL要做出相应处理。
万能语句:
要确定head与head->next均不为NULL,所以就添加下面的语句即可:
while((head==NULL)||(head->next==NULL))
return head;