/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
struct ListNode* deleteDuplicates(struct ListNode* head )
{
//write code here
//当链表为空或者链表只有一个元素
if(head==NULL || head->next==NULL)
return head;
//创造一个头结点作为新链表
struct ListNode* H=(struct ListNode* )malloc(sizeof(struct ListNode));
H->next=NULL;
struct ListNode* pi;
pi=H;
struct ListNode* cur;//定义遍历节点
struct ListNode* nex;//定义下一个结点
struct ListNode* pre;//定义前一个节点
struct ListNode* pH=(struct ListNode* )malloc(sizeof(struct ListNode));
pH->next=head;
pre=pH;
cur=head;
while(cur!=NULL)
{
nex=cur->next;
//因为nex不为空
if(nex!=NULL)
{
//头结点
if(cur==head)
{
if( cur->val!=nex->val)
{
struct ListNode* Node=(struct ListNode* )malloc(sizeof(struct ListNode));
Node->val=cur->val;
Node->next=NULL;
pi->next=Node;
pi=pi->next;
}
pre=pre->next;
cur=nex;
}
else
{
if( cur->val!=nex->val && cur->val!=pre->val)
{
struct ListNode* Node=(struct ListNode* )malloc(sizeof(struct ListNode));
Node->val=cur->val;
Node->next=NULL;
pi->next=Node;
pi=pi->next;
}
pre=pre->next;
cur=nex;
}
}
else
{
//不相同
if( cur->val!=pre->val)
{
struct ListNode* Node=(struct ListNode* )malloc(sizeof(struct ListNode));
Node->val=cur->val;
Node->next=NULL;
pi->next=Node;
pi=pi->next;
}
pre=pre->next;
cur=nex;
}
}
return H->next;
}
解题思路:只要该结点数值与前后数值不一样,就说明该结点是不重复元素
难点:因为后节点nex有出现null的情况,所以判断的时候,当nex=null时,nex->val是错误的,所以要单拎出来判断
注意:取val判断时,一定要注意它是不是空结点,否则就会出错;