Algorithm leetcode|83. Delete duplicate elements in sorted linked list (rust strikes hard)



83. Remove duplicate elements from a sorted linked list:

Given the head of a sorted linked list head, remove all duplicate elements so that each element appears only once. Returns a sorted linked list.

Example 1:

输入:
	
	head = [1,1,2]
	
输出:
	
	[1,2]

Example 2:

输入:
	
	head = [1,1,2,3,3]
	
输出:
	
	[1,2,3]

hint:

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

analyze:

  • Facing this algorithm question, the second master once again fell into deep thought.
  • Originally, to remove duplicate elements, two traversals were required, or a data structure with extra space, such as a mapping table.
  • But the title says it is sorted, that is to say, the same elements will be next to each other.
  • If it is an array, then we should traverse it in rounds to determine whether each element is the same as the previous element.
  • But the question is about a sorted linked list. The characteristic of a one-way linked list is that it can only be traversed from front to back, so what we need to judge is whether the current element and the next element are the same. If they are the same, delete the next element.
  • What should be noted is to judge the end of the linked list. The length of the linked list cannot be directly known. It needs to be traversed all the time to determine whether it has reached the end. Usually, it is judged whether the end of the linked list has been reached based on whether the next node is empty.
  • In addition, you need to pay attention to the possibility that the linked list does not have any nodes and is directly empty. If you directly loop through to determine whether the next node is empty, it will be abnormal, so you need to do a pre-check first.
  • Every time I write Rust to access the linked list, I feel a little speechless. It’s really a bit verbose, but there’s nothing I can do about it. Just because our memory is safe, it’s worth it. This paragraph is not really a complaint. Rust is very easy to use. I just made up the word count. etc., but the learning curve of rust is relatively high.

answer:

rust:

// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
    
    
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
    
    
//   #[inline]
//   fn new(val: i32) -> Self {
    
    
//     ListNode {
    
    
//       next: None,
//       val
//     }
//   }
// }
impl Solution {
    
    
    pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    
    
        if head.is_none() {
    
    
            return head;
        }

        let mut head = head;
        let mut cur = head.as_mut().unwrap();

        while cur.next.is_some() {
    
    
            if cur.val == cur.next.as_ref().unwrap().val {
    
    
                cur.next = cur.next.as_mut().unwrap().next.take();
            } else {
    
    
                cur = cur.next.as_mut().unwrap();
            }
        }

        return head;
    }
}

go:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
    
    
    if head == nil {
    
    
		return nil
	}

	cur := head
	for cur.Next != nil {
    
    
		if cur.Val == cur.Next.Val {
    
    
			cur.Next = cur.Next.Next
		} else {
    
    
			cur = cur.Next
		}
	}

	return head
}

c++:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* deleteDuplicates(ListNode* head) {
    
    
        if (!head) {
    
    
            return head;
        }

        ListNode *cur = head;
        while (cur->next) {
    
    
            if (cur->val == cur->next->val) {
    
    
                cur->next = cur->next->next;
            } else {
    
    
                cur = cur->next;
            }
        }

        return head;
    }
};

python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return head

        cur = head
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next

        return head


java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode deleteDuplicates(ListNode head) {
    
    
        if (head == null) {
    
    
            return null;
        }

        ListNode cur = head;
        while (cur.next != null) {
    
    
            if (cur.val == cur.next.val) {
    
    
                cur.next = cur.next.next;
            } else {
    
    
                cur = cur.next;
            }
        }

        return head;
    }
}

Thank you very much for reading this article~
Welcome to [Like] [Collect] [Comment] Three in a row ~ It
is not difficult to give up, but it must be cool to persist ~
I hope we can all make a little progress every day ~
This article is written by the second-in-command white hat: https://le-yi.blog.csdn.net/Original blog~


Guess you like

Origin blog.csdn.net/leyi520/article/details/132970124