LeetCode之Remove Duplicates from Sorted List
2014-01-28 13:16
309 查看
【题目】
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】
/********************************* * 日期:2014-01-28 * 作者:SJF0115 * 题号: Remove Duplicates from Sorted List * 来源:http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/ * 结果:AC * 来源:LeetCode * 总结: **********************************/ #include <iostream> #include <stdio.h> #include <algorithm> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(head == NULL){ return head; } //记录上一节点的值 int preVal = head->val; ListNode *pre = head,*cur = head->next; while(cur != NULL){ //如果相同则删除cur节点 if(cur->val == preVal){ pre->next = cur->next; cur = pre->next; } else{ preVal = cur->val; pre = cur; cur = cur->next; } } return head; } }; int main() { Solution solution; int A[] = {1,1,1,4,4,6}; ListNode *head = (ListNode*)malloc(sizeof(ListNode)); head->next = NULL; ListNode *node; ListNode *pre = head; for(int i = 0;i < 6;i++){ node = (ListNode*)malloc(sizeof(ListNode)); node->val = A[i]; node->next = NULL; pre->next = node; pre = node; } head = solution.deleteDuplicates(head->next); while(head != NULL){ printf("%d ",head->val); head = head->next; } return 0; }
相关文章推荐
- Java Thread 多线程同步、锁、通信
- 遍历list集合
- 为什么负数取补码---转自百度知道
- Maven仓库中添加Oracle驱动包
- makefile编译所有cpp文件
- 【Android病毒分析报告】 - AVPasser 对抗安全软件监控
- webservices使用的介绍
- Google C++编程风格指南
- TechYY系列之二:iPhone 配备三摄像头?
- 为什么优秀的程序员既懒又笨
- Codeforces Beta Round #1 A B C
- Google Java编程风格指南
- SPLUNK 安装配置及常用语法
- 你应该这样写”年度总结“
- 管理小故事1-怎么给这个部门经理发年终奖
- tcpdump的使用
- NSURLSession使用说明及后台工作流程分析
- Bootstrap2中同一页面实现多个modal
- 编程挑战 分巧克力
- 进程间通信---匿名管道pipe