题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
解题思路
不怎么标准的程序流程图
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode listNode = new ListNode(0);
listNode = head;
if (listNode == null)
return head;
while (listNode.next != null) {
if (listNode.val == listNode.next.val) {
listNode.next = listNode.next.next;
} else {
listNode = listNode.next;
}
}
return head;
}
}