Remove Duplicates from Sorted List
来源:互联网 发布:php arg 编辑:程序博客网 时间:2024/05/24 04:58
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.`
leetcode里面有一个类似的题目,只不过操作对象不同而已,之前那个是对数组删除重复数,这里只不过变成链表而已。
这里我就把两个问题的解决方案都写出来。
1首先是数组,数组的思路就是另外设置一个参数K,让K指向A[0],对数组进行遍历,如果A[k]!=A[i],则用A[k]记录下这个数,k自增1;
int removeDuplicates(int A[], int n) { int i,k=0; if(n==0)return 0; if(n==1)return 1; for(i=1;i<n;i++) { if(A[k]!=A[i]) { k++; A[k]=A[i]; } } return k+1;}
2 如果是对链表进行这样的操作,只需要设置两个指针,一个指向另一个的后继,判断两个的val是否相等,如果相等那么删除后继节点,如果不相等,两个指针都指向后继的节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode *deleteDuplicates(struct ListNode *head) { struct ListNode *p,*q; if(head==NULL||head->next==NULL)return head; p=head; q=head->next; while(q) { if(q->val==p->val) { p->next=q->next; q=q->next; } else { p=p->next; q=q->next; } } return head;}
0 0
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove duplicates from sorted list
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- HTML之visibility和display属性小议
- CABasicAnimation animationWithKeyPath 一些规定的值
- iOS获取ipa里的资源如图片等
- 第三周 项目5-1 工资类
- (三)Multi-class Classification and Neural Networks[多分类问题和神经网络]
- Remove Duplicates from Sorted List
- Linux 静态库与共享库的使用
- 一、 编译Live555
- 深入理解Java多态性
- flex与socket通信之成功
- 关于Eclipse中导入Android工程遇到的问题
- size, length, numel function in matlab
- iOS 应用内下载
- 欢迎使用CSDN-markdown编辑器