链表经典问题之删除链表元素专题笔记
leetcode203. 移除链表元素
解题思路 1。创建一个虚拟表头dummy,dummy->next=head
2.遍历链表元素,寻找目标元素,使用cur->next->val来判断
3.找到目标元素,使用cur->next=cur->next->next;
4,最后要返回dummy->next
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* dummyHead=(struct ListNode*)malloc(sizeof(struct ListNode));
dummyHead->next=head;
//dummyHead->val = 0;
struct ListNode* cur = dummyHead;
while(cur->next!=NULL)
{
if(cur->next->val==val)
{
cur->next=cur->next->next;
}
else
{
cur=cur->next;
}
}
return dummyHead->next;
}
leetcode19.删除倒数第n个结点
解题思路
1.遍历链表,得出链表总长度L,L-N+1就是我们要删除的元素,
注意链表从0开始标号的(比如0.1.2.3)
int getlength(struct ListNode*p)
{
int length=0;
while(p!=NULL)
{
length++;
p=p->next;
}
return length;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode* dummy=(struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next=head;
int length=getlength(head);
struct ListNode* cur=dummy;
for(int i=1;i<length-n+1;i++)
{
cur=cur->next;
}
cur->next=cur->next->next;
return dummy->next;
}
删除重复元素
1.重复元素保留一个leetcode83
struct ListNode* deleteDuplicates(struct ListNode* head)
{
struct ListNode* cur=(struct ListNode*)malloc(sizeof(struct ListNode));
cur=head;
if(head==NULL)
{
return head;
}
while(cur->next!=NULL)
{
if(cur->val==cur->next->val)
{
cur->next=cur->next->next;
}
else
cur=cur->next;
}
return head;
}
== 2.重复元素都不要leetcode82==
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head==NULL)
{
return head;
}
struct ListNode* dummy=(struct ListNode*)malloc(sizeof(struct ListNode));
dummy->val=0;
dummy->next=head;
struct ListNode* cur=(struct ListNode*)malloc(sizeof(struct ListNode));
cur=dummy;
while(cur->next!=NULL&& cur->next->next!=NULL)
{
if(cur->next->val==cur->next->next->val)
{
int x=cur->next->val;
while(cur->next!=NULL && cur->next->val==x)
{
cur->next=cur->next->next;
}
}
else
cur=cur->next;
}
return dummy->next;
}