删除链表中的重复元素I

xiaoxiao2021-02-28  81

删除排序链表中的重复元素  给定一个排序链表,删除所有重复的元素每个元素只留下一个。 给出 1->1->2->null,返回 1->2->null

给出 1->1->2->3->3->null,返回 1->2->3->null

import java.util.Scanner; /** * 删除排序链表中的重复元素 给定一个排序链表,删除所有重复的元素每个元素只留下一个。 您在真实的面试中是否遇到过这个题? Yes 样例 给出 1->1->2->null,返回 1->2->null 给出 1->1->2->3->3->null,返回 1->2->3->null * * @author Dell * */ public class Test112 { public static ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null||head.next.next==null) return head; ListNode q=head.next; ListNode p=q.next; while(p!=null) { int temp=q.val; boolean flag=false; while(p!=null&&p.val==temp) { p=p.next; flag=true; } if(flag==true) { q.next=p; } q=q.next; if(p!=null) p=p.next; } return head; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ListNode list=new ListNode(-1); ListNode p=list; for(int i=0;i<n;i++) { ListNode temp=new ListNode(sc.nextInt()); p.next=temp; p=p.next; } ListNode result=deleteDuplicates(list); ListNode q=result.next; while(q!=null) { System.out.print(q.val+" "); q=q.next; } } }

转载请注明原文地址: https://www.6miu.com/read-51710.html

最新回复(0)