题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
主要思路:
设置双指针,第一个指针l1指向的先是head,然后遍历全链表;第二个指针l2先指向l1的下一个结点,往后遍历,若找到一个val值相等的结点,设置isRepeat值标记l1,然后删掉此结点,最后删掉l1。
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
ListNode l1 = head; //第一个指针l1
int isRepeat;
while (l1!=null && l1.next!=null) {
isRepeat = 0; //用于标记l1是否为重复元素
ListNode l2 = l1.next; //第二个指针l2
while (l2!=null) {
if (l2.val==l1.val) {
isRepeat = 1;
//删掉l2指向结点
ListNode l4 = head;
while (l4.next!=l2)
l4 = l4.next;
l4.next = l2.next;
l2 = l4;
}
l2 = l2.next;
}
//若存在重复元素
if (isRepeat==1) {
//l1为头结点的情况
if (l1==head) {
head = l1.next;
l1 = head;
continue;
}
else {
ListNode l3 = head;
while (l3.next!=l1)
l3 = l3.next;
l3.next = l1.next;
l1 = l3;
continue;
}
}
l1 = l1.next; //继续向后遍历
}
return head;
}
}
