LintCode之删除排序链表中的重复元素

题目描述:

我的代码:

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param head: head is the head of the linked list
17      * @return: head of linked list
18      */
19     public ListNode deleteDuplicates(ListNode head) {
20         // write your code here
21         if(head == null) {
22             return null;
23         }
24         //新建一个链表,h节点作为头节点,将链表的第一个值赋给它
25         ListNode h = new ListNode(head.val);
26         ListNode p = h;
27         while(head.next != null) {
28             head = head.next;
29             if(head.val != p.val) {
30                 ListNode node = new ListNode(head.val);
31                 p.next = node;
32                 p = p.next;
33             }
34            
35         }
36         return h;
37     }
38 }

总结:因为链表是已经排好序的,所以相同的元素是在一起的。

posted @ 2017-10-26 13:51  zwt3  阅读(701)  评论(0编辑  收藏  举报