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