[Java] 83. Delete the repeated elements in the sorted linked list --- Use a while loop to solve the problem, the idea is simplified, the time complexity is O(N)

There is a linked list arranged in ascending order. Give you the head node of this linked list. Please delete all the repeated elements so that each element only appears once.

Return a linked list of results also sorted in ascending order.
Example 1:

Input: head = [1,1,2]
Output: [1,2]Insert picture description here

prompt:

The number of nodes in the linked list is within the range [0, 300]
-100 <= Node.val <= 100 The
question data ensures that the linked list has been arranged in ascending order

复杂代码:运行时间1MS
public ListNode deleteDuplicates(ListNode head) {
    
    
		  ListNode p=head,p1=head;
		  if(head==null||head.next==null) {
    
    
			  return head;
		  }
		  int a=head.val;
		  p=p.next;
		  while(p!=null) {
    
    
			  if(p.val==a) {
    
    
				  while(p!=null) {
    
    
					  if(p.val!=a) {
    
    
						  p1.next=p;
						  p1=p1.next;
						  a=p.val;
						  p=p.next;
						  break;
					  }
					 p=p.next;
				  }
			  }else {
    
    
				  p1.next=p;
				  p1=p1.next;
				  a=p.val;
				  p=p.next;
			  }
			  
		  }
		  if(p==null) {
    
    
			  p1.next=null;
			  return head;
		  }
    	  return head;
      }
修改版代码:运行时间0MS
public ListNode deleteDuplicates(ListNode head) {
    
    
		  ListNode p=head,p1=head;
		  if(head==null||head.next==null) {
    
    
			  return head;
		  }
		  int a=head.val;
		  p=p.next;
		  while(p!=null) {
    
    
			  if(p.val!=a) {
    
    
				  p1.next=p;
				  p1=p1.next;
				  a=p.val;
			  }
              p=p.next; 
		  }
		  if(p==null) {
    
    
			  p1.next=null;
			  return head;
		  }
    	  return head;
      }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115231191