题目描述:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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) {
if(head == null || head.next == null)
return head;
ListNode cur=head;
while(cur.next!=null ){
if(cur.val == cur.next.val){
//将下一个节点和当前节点进行比较,如果两者相等,那就将下下个节点接到这个节点的后面,相当于将重复的节点摘除了.
cur.next=cur.next.next;
}else{
cur=cur.next;
}
}
return head; //返回头结点后所有元素(头结点带数据)
}
}