首页 > 其他 > 详细

LeetCode(83):Remove Duplicates from Sorted List

时间:2016-01-15 22:36:05      阅读:175      评论:0      收藏:0      [点我收藏+]

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.

题意:删除链表中重复的元素值,保留一个。

思路:双指针,首先判断链表是否为空或者只包含一个元素,如果是则返回头指针head,否则定义双指针p和q,p初始化指向head.next,q指向head,然后遍历链表,判断p和q所指向节点元素值是否相同,相同的话删除,不相同的话分别指向下一个结点。

代码:

public ListNode deleteDuplicates(ListNode head) {
          if (head==null||head.next==null) return head;
           ListNode p = head.next;
           ListNode q = head;
           while(p!=null){
               if(p.val==q.val){
                   p=p.next;
                   q.next=q.next.next;
               }else{
                   p=p.next;
                   q=q.next;
               }
           }
           return head;
         
    }

LeetCode(83):Remove Duplicates from Sorted List

原文:http://www.cnblogs.com/Lewisr/p/5134466.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!