码迷,mamicode.com
首页 > 其他好文 > 详细

56删除链表中重复的结点

时间:2018-01-11 20:34:27      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:class   返回   blog   处理   nod   val   排序   dup   ica   

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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 }

 


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

 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         ListNode newtempp = newhead;
17         while(head!=null && head.next!=null){
18             if(head.val == head.next.val){
19                 int val = head.val;
20                 while(head!=null && val==head.val)
21                     head = head.next;
22                 newtempp.next = head;
23             }
24             else{
25                 newtempp=head;
26                 head = head.next;
27             }
28         }
29    
30         return newhead.next;
31     }
32 }

 

56删除链表中重复的结点

标签:class   返回   blog   处理   nod   val   排序   dup   ica   

原文地址:https://www.cnblogs.com/zle1992/p/8270230.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!