数据结构—线性结构—链表:(删除排序链表中的重复元素)
一、题目:给定一个排序链表,删除所有重复的元素每个元素只留下一个。
样例:
给出 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;
}
}