【经典算法】Leetcode.83删除排序链表中的重复元素(Java/C/Python3/Go实现含注释说明,Easy)
题目:删除排序链表中的重复元素
解法:遍历链表,并比较当前节点与下一节点的值,如果发现重复,则跳过下一节点并释放它。
Java 实现:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode current = head;
while (current.next != null) {
if (current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}
C 实现:
struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL) {
return head;
}
struct ListNode* current = head;
while (current->next != NULL) {
if (current->val == current->next->val) {
current->next = current->next->next;
} else {
current = current->next;
}
}
return head;
}
Python3 实现:
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
current = head
while current.next:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next
return head
Go 实现:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil {
return head
}
current := head
for current.Next != nil {
if current.Val == current.Next.Val {
current.Next = current.Next.Next
} else {
current = current.Next
}
}
return head
}
评论已关闭