- Remove Duplicates from Sorted Ar
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- Remove Duplicates from Sorted Li
- remove duplicates from sorted li
题目描述
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
分析:给定一个有序链表,去除重复元素,并返回一个新链表。
我的Code如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return head;
}
ListNode pre = head;
ListNode cur = head.next;
while(cur != null){
if(pre.val == cur.val){
pre.next = cur.next;
}else{
pre = cur;
}
cur = cur.next;
}
return head;
}
}
网友评论