标签:style blog class code c tar
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
题意:去掉已排序的链表里重复的元素
思路:
1.遍历链表,用一个变量保存当前链表节点的值
2.如果当前链表节点值与前面的一样,则删除当前链表节点
3.否则用当前节点值更新该变量
复杂度:时间O(n), 空间O(1)
相关题目:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(!head) return NULL; ListNode *pre = head; ListNode *cur = head->next; while(cur){ if(cur->val == pre->val){ //delete current node pre->next = cur->next; delete cur; cur = pre->next; }else{ //update value pre = cur; cur = cur->next; } } return head; } };
Leetcode 线性表 Remove Duplicates from Sorted List,布布扣,bubuko.com
Leetcode 线性表 Remove Duplicates from Sorted List
标签:style blog class code c tar
原文地址:http://blog.csdn.net/zhengsenlie/article/details/25776319