删除有序链表中重复的数据

package leetcode.LinkedList83;

/**

  • Definition for singly-linked list.

  • public class ListNode {

  • int val;
    
  • ListNode next;
    
  • ListNode(int x) { val = x; }
    
  • }
    */
    class Solution {
    public ListNode deleteDuplicates(ListNode head) {
    if(head == null) {
    return null;
    }
    //原链表的当前节点
    ListNode cur = head.next;

     //创建一个新的链表
     ListNode newHead = new ListNode(head.val);
     ListNode newList_cur = newHead;
    
     while(cur!=null){
         //如果新的链表中没有这个节点,那么就添加进去
         if(!contains(newHead,cur.val)){
             newList_cur.next = new ListNode(cur.val);
             newList_cur = newList_cur.next;
         }
         cur = cur.next;
     }
     return newHead;
    

    }

    //检测链表中是否包含某个元素
    boolean contains(ListNode head,int val){
    while(head != null){
    if(head.val == val){
    return true;
    } else {
    head = head.next;
    }
    }
    return false;
    }
    public static void main(String[] args) {
    int arr[] = {1,2,3,4,3,5,6};
    ListNode head = new ListNode(arr);
    System.out.println(head);

     ListNode ret = (new Solution()).deleteDuplicates(head);
     System.out.println("最终结果:"+ret);
    

    }
    }
    #方法二
    import java.util.LinkedList;

public class DeleteLinkData {

public static void main(String[] args) {
	//删除排序链表重复的节点
	LinkedList list=new LinkedList<>();
    int[] source= {4,5,7,7,8,22};
    for(int data:source) {
    	list.add(data);
    }
    if(list!=null||list.size()!=1) {
    	for(int j=0;j<list.size()-1;j++) {
    		if(list.get(j)==list.get(j+1)) {
    			list.remove(j);
    		}
    	}
    	for(int i=0;i<list.size();i++) {
    		System.out.println(list.get(i));
    	}
    }
}

}

猜你喜欢

转载自blog.csdn.net/weixin_37565521/article/details/87711060