原题
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
翻译
给你一个链表,删掉其中重复的,使每个元素只出现一次。
例 1:
输入: 1->1->2
输出: 1->2
例 2:
输入: 1->1->2->3->3
输出: 1->2->3
程序
1. 思路一
当数字不同时,直接将上一种数字第一个,指向当前数字第一个
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head==NULL||head->next==NULL)return head;
struct ListNode* now = head;
struct ListNode* prev_node = head;
int prev = head->val;
while(now != NULL)
{
if(prev_node->val != now -> val )
{
prev_node->next = now;
prev_node = now;
}
if( now->next==NULL)
prev_node->next = NULL;
now = now->next;
}
return head;
}
2. 思路二
当前节点与下一个进行比较,相同就让当前节点指向下下个节点
别人的程序
总结
- 思路一效率并不高,定义了较多变量占据内存空间