题目:删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次。
思路:链表遍历:前后结点的值相等,则删除后边的这个结点,如果不相等结点后移。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if(head == null) return null;
if(head.next == null) return head;
ListNode tmp = head;
while( tmp!= null && tmp.next!=null){
if(tmp.val == tmp.next.val){
tmp.next = tmp.next.next;
}else{
tmp = tmp.next;
}
}
return head;
}
}