题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
http://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
删除重复值可以选择用一个节点当做参考,找到下一个不是一样的值,然后将第一个值得next设置为这个参考节点
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 || head.next == null) {
return head;
}
ListNode res = head;
ListNode temp = head.next;
while (res != null && res.next != null) {
//当这个临时节点为空时,代表已经到末尾此时只需要将第一个重复节点得next设为null
//然后结束
if (temp == null) {
res.next = temp;
return head;
}
if (res.val == temp.val) {
temp = temp.next;
} else {
res.next = temp;
res = res.next;
}
}
return head;
}
}