Remove Duplicates from Sorted List II

<span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px; background-color: rgb(255, 255, 255);">先看这样一道题:</span>

Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        if(node==null)
            return;
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

注意这里我们并不是真的删除了3的那个节点(已题为例),只是将3的那个节点的知道换成下一个节点的值,然后把3这个节点的指针指向下一个节点的下一个节点(因为4那个节点我们放到3哪里了)

再看这题

Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

一开始我想用上面的思路,当指针指向3的时候我先把后面的那个3删除,然后用上一题的方法来把第一次出现的3删了,但最后发现不行,我们注意第一题的题目中说了删的那个节点不是最后一个,为什么要加这一句话???,在本题中如果我们要删除的节点是最后一个,那么就会出现问题了。因为我们无法做到真正的删除(因为没有指向前一个节点的指针)。所以要想删除一个节点,一定要知道前一个节点的指针的。最后给出这题的code)(注意我增加了一个假的头结点)

<span style="font-size:14px;">/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null)
            return null;
        ListNode fakehead = new ListNode(-1);
        fakehead.next = head;
        ListNode p = fakehead,p1 = head;
        int flag = 0;
        while(p1!=null&&p1.next!=null){
          if(p1.val==p1.next.val){
              p1 = p1.next;
              flag = 1;
          }
          else{
              if(flag==0){
                  p = p.next;
                  p1 = p.next;
              }
              else{
                  p.next = p1.next;
                  flag = 0;
                  p1 = p.next;
              }
          }
        }
        /*if we need to delete the last node,like this 1->2->3->3->3.
            we need to add below code        
        */
        if(flag==1){
              p.next = p1.next;
        }
       
        return fakehead.next;
    }
}</span><span style="font-size: 24px;">
</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值