zoukankan      html  css  js  c++  java
  • 56删除链表中重复的结点

    题目描述

    在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1→2->5


    没审题,写成了链表去重
    1->2->3->3->4->4->5 处理后为 1→2→3——4-----5

     1 /*
     2  public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }
    10 */
    11 public class Solution {
    12     public ListNode deleteDuplication(ListNode head){
    13     if(head==null || head.next ==null) return head;
    14     ListNode newhead = head;
    15     ListNode newpp = newhead;
    16     for(ListNode p = head.next;p!=null;p=p.next){
    17         if(p.next!=null && p.val==p.next.val)
    18             p = p.next;
    19         ListNode newtempp= new ListNode(p.val);
    20         newtempp.next = null;
    21         newpp.next = newtempp;
    22         newpp = newtempp;
    23         newtempp = newtempp.next;
    24     }
    25   
    26     return newhead;
    27     }
    28 }

    注意是排序链表!!!

    为了保证删除之后的链表仍然是相连的而没有断开,我们要把当前的节点(head)和后面的节点和后面比当前节点的值要大的节点(next)相连。

     1 /*
     2  public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }
    10 */
    11 public class Solution {
    12     public ListNode deleteDuplication(ListNode head){
    13         if(head==null || head.next ==null) return head;
    14         ListNode newhead = new ListNode(-1);
    15         newhead.next = head;
    16         head = newhead;
    17         ListNode next = head.next;
    18         while(next!=null && next.next!=null){
    19             if(next.val == next.next.val){
    20                 int val = next.val;
    21                 while(next!=null && val==next.val)
    22                     next = next.next;
    23                 head.next = next;
    24             }
    25             else{
    26                 head=next;
    27                 next = next.next;
    28             }
    29         }
    30         return newhead.next;
    31     }
    32 }
  • 相关阅读:
    vue富文本编辑器
    vue图片上传组件
    vue全局使用axios插件请求ajax
    vue项目初始化时npm run dev报错webpack-dev-server解决方法
    vue axios使用form-data的形式提交数据
    react-keep-alive
    create-react-app 兼容 ie9
    next-定义路由
    next-支持css样式和按需加载antd
    react-错误边界
  • 原文地址:https://www.cnblogs.com/zle1992/p/8270230.html
Copyright © 2011-2022 走看看