题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表 1->2->3->3->4->4->5 处理后为 1->2->5
public ListNode deleteDuplication(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
while(cur != null){
while(cur.next != null && cur.val == cur.next.val){//查找重复的节点
cur = cur.next;
}
if(pre.next == cur){ //没有重复的节点,向前移动前一个节点
pre = cur;
}
else{ //代表有重复的节点(当前节点是最后一个重复的节点),前一个节点指向当前节点的下一个节点
pre.next = cur.next;
}
cur = cur.next;
}
return dummy.next;
}
另外一种解法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
if(cur.next.val == cur.next.next.val){
int value = cur.next.val;
while(cur.next != null && cur.next.val == value){
cur.next = cur.next.next;
}
}
else{
cur = cur.next;
}
}
return dummy.next;
}
}
其他解法:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
pre.next = head;
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.val == cur.next.val){
int val = cur.val;
while(cur != null && cur.val == val){
cur = cur.next;//最终cur不等于之前的值
}
pre.next = cur;
}
else{
pre = cur;
cur = cur.next;
}
}
return dummy.next;
}
}
类似题目Leetcode 83
删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次,
思路分析:
首先,链表为空直接返回
其次,如果当前结点值与下一结点的值相等
最后要注意一下else的位置,比如说结点1和2比较后相等把2消去,这个时候就不能把指针指向下一结点了,要继续比较1和3,所以消去结点和指向下一结点只能二选一
public ListNode deleteDuplicates (ListNode head) {
if(head == null){
return head;
}
ListNode cur = head;
while(cur.next != null){
//结点1和2比较后相等把2消去,这个时候就不能把指针指向下一结点了,要继续比较1和3
if(cur.val == cur.next.val){
cur.next = cur.next.next;
}
else{
cur = cur.next;
}
}
return head;
}