您的位置:首页 > 其它

LintCode—删除排序链表中的重复元素(112)

2018-03-29 21:53 363 查看

数据结构—线性结构—链表:(删除排序链表中的重复元素)

一、题目:给定一个排序链表,删除所有重复的元素每个元素只留下一个。

样例:给出 
1->1->2->null
,返回 
1->2->null
给出 
1->1->2->3->3->null
,返回 
1->2->3->null

二、分析:

需要考虑的点:
            1.链表为空

            2.链表只有一个元素

三、代码

/**
* 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) {
ListNode listNodeHead = new ListNode(0);
listNodeHead.next = head;
ListNode probeNode = new ListNode(0);

while(head != null){
probeNode = head.next;
while(probeNode !=null && probeNode.val == head.val){
probeNode = probeNode.next;
head.next = probeNode;
}
head = head.next;
}
return listNodeHead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: