【Leetcode】Remove Duplicates from Sorted List

来源:互联网 发布:程序员找工作 编辑:程序博客网 时间:2024/06/15 17:03

原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

题目:

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.

思路:

算法:

[java] view plain copy
  1. public ListNode deleteDuplicates(ListNode head) {  
  2.     ListNode p = head, q;  
  3.     if (p == null) {  
  4.         return head;  
  5.     }  
  6.     q = p.next;  
  7.     while (q != null) {  
  8.         if (p.val == q.val) {  
  9.             p.next = q.next;  
  10.         } else {  
  11.             p = q;  
  12.         }  
  13.         q = q.next;  
  14.     }  
  15.     return head;  
  16. }  
0 0
原创粉丝点击