leetcode之Remove Duplicates from Sorted List
2016-04-03 16:54
323 查看
核心思想就是相邻元素逐个比较,遇到相等的就将排在后面的删除。
(1)C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(head == NULL)
return NULL;
struct ListNode* p = head;
while(p!=NULL && p->next!=NULL){
if(p->val == p->next->val){
p->next = p->next->next;
}
else
p = p->next;
}
return head;
}
(2)C++实现
/**
* 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 == NULL)
return NULL;
ListNode* p = head;
while(p!=NULL && p->next!=NULL){
if(p->val == p->next->val){
p->next = p->next->next;
}
else
p = p->next;
}
return head;
}
};
(3)java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null)
return null;
ListNode p = head;
while(p!=null && p.next!=null){
if(p.val == p.next.val){
p.next = p.next.next;
}
else
p = p.next;
}
return head;
}
}
(1)C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(head == NULL)
return NULL;
struct ListNode* p = head;
while(p!=NULL && p->next!=NULL){
if(p->val == p->next->val){
p->next = p->next->next;
}
else
p = p->next;
}
return head;
}
(2)C++实现
/**
* 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 == NULL)
return NULL;
ListNode* p = head;
while(p!=NULL && p->next!=NULL){
if(p->val == p->next->val){
p->next = p->next->next;
}
else
p = p->next;
}
return head;
}
};
(3)java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null)
return null;
ListNode p = head;
while(p!=null && p.next!=null){
if(p.val == p.next.val){
p.next = p.next.next;
}
else
p = p.next;
}
return head;
}
}
相关文章推荐
- Java并发编程系列之十:synchronized(1)
- 堆排序
- linux基本目录结构知识总结
- 状态栏的停留时间信息_JS特效代码
- rpi qemu linux 4.1.x .config
- 排序算法 及其稳定性解释
- ARToolKit for Unity Scripting and Low-Level API
- Hadoop 2.x搭建详解 centos
- Python中生成唯一ID的库——UUID
- 脚本引擎Rhino执行javascript代码
- UVA_216_Getting in Line_brute_force
- Android之Service
- 一个完整的PHP类包含的七种语法说明
- leetcode之Odd Even Linked List
- 状态栏的进度条_JS特效代码
- 我与小娜(47):在清明时节,探讨与亡灵对话的可能性
- 蜥蜴[SCOI2007,BZOJ 1066]
- Android设计模式应用---原型模式
- Android自定义滑动接听电话控件组
- 剑指offer刷题系列说明