给你一个链表,需要你返回一个去重后的链表,并且得到它的长度,额外需要注意的是如果头节点或者投节点的下一个节点为空,则返回头节点
时间: 2023-05-19 14:04:16 浏览: 79
好的,我可以回答这个问题。以下是一个去重后的链表的实现代码,同时也会返回链表的长度:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeDuplicates(head: ListNode) -> ListNode:
if not head:
return None
curr = head
while curr.next:
if curr.val == curr.next.val:
curr.next = curr.next.next
else:
curr = curr.next
return head
def getLength(head: ListNode) -> int:
length = 0
curr = head
while curr:
length += 1
curr = curr.next
return length
# 测试代码
head = ListNode(1, ListNode(1, ListNode(2, ListNode(3, ListNode(3)))))
new_head = removeDuplicates(head)
print(getLength(new_head)) # 输出 3
```
希望这个代码可以帮到你!
阅读全文