每日一题
删除有序链表中重复的元素——I
思路
给定个链表已经有序,那这就好办了,我们只需要从头遍历整个链表,比较相邻元素,再删除重复元素即可,
方法一(双指针)
- 如果链表为空或只有一个节点,则直接返回头结点
- 先新建一个头结点newhead,使其指向第一个节点,这样,如果我们要删除第一个节点,返回的时候,直接返回newhead->就可以了.
- 定义三个指针变量pre,slow,fast,使其分别指向newhead,head,head->next
- 每次让slow,fast每次走一个节点,若slwo的值等于fast的值,则删除slow节点,若不等,则继续遍历链表,直到fast为空,即遍历完毕.
- 返回newhead->next
实现代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
struct ListNode* deleteDuplicates(struct ListNode* head ) {
if(head == NULL || head->next == NULL)
return head;
struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* pre = newhead, *slow = head, *fast = head->next;
newhead->next = head;
while(fast)
{
if(slow->val != fast->val)
{
pre = slow;
slow = fast;
fast = fast->next;
}
else
{
slow = fast;
fast = fast->next;
pre->next = slow;
}
}
return newhead->next;
}
方法二(单指针)
- 定义指针变量cur指向第一个节点,遍历链表
- 如果cur的数据域等于下一个节点的数据,那么令cur的指针域指向cur的下下个节点,如果不等,则令cur下滑一个节点,直到cur或cur的下一个节点为空
- 返回头结点
实现代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
struct ListNode* deleteDuplicates(struct ListNode* head ) {
if(head == NULL || head->next == NULL)
return head;
struct ListNode *cur = head;
while(cur && cur->next)
{
if(cur->val == cur->next->val)
cur->next = cur->next->next;
else
cur = cur->next;
}
return head;
}