题目描述:

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

我的代码:

 /**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ public class Solution {
/*
* @param head: head is the head of the linked list
* @return: head of linked list
*/
public ListNode deleteDuplicates(ListNode head) {
// write your code here
if(head == null) {
return null;
}
//新建一个链表,h节点作为头节点,将链表的第一个值赋给它
ListNode h = new ListNode(head.val);
ListNode p = h;
while(head.next != null) {
head = head.next;
if(head.val != p.val) {
ListNode node = new ListNode(head.val);
p.next = node;
p = p.next;
} }
return h;
}
}

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

05-27 06:39