对于链表中任何绝对值相等的结点,仅保留第一次出现的结点,而删除其余绝对值相等的结点
时间: 2023-05-29 08:06:27 浏览: 87
可以使用哈希表来实现。遍历链表的每个结点,将其绝对值作为哈希表的键,结点本身作为值存储在哈希表中。如果当前结点的绝对值已经在哈希表中出现过,则将当前结点从链表中删除,否则将当前结点加入哈希表。
以下是具体的代码实现:
```python
def remove_duplicate_abs(head):
if not head or not head.next:
return head
seen = {} # 哈希表,存储已经出现的绝对值
curr = head
prev = None # 当前结点的前一个结点,用于删除结点
while curr:
if abs(curr.val) in seen:
prev.next = curr.next
else:
seen[abs(curr.val)] = True
prev = curr
curr = curr.next
return head
```
时间复杂度为 $O(n)$,空间复杂度为 $O(n)$。
相关问题
用单链表保存m个整数,结点的结构为: [data | link]且|data|≤n(n为正整数)。现要求设计一个时间复杂度尽可能高效的算法,对于链表中data的绝对值相等的结点,仅保留第一次出现的结点而删除其余绝对值相等的结点。(1≤m,|n|≤10000)例如,若给定的单链表head如下:
好的,你的问题是关于单链表的算法,我会尽力回答。根据你的要求,我们需要遍历整个链表并记录每个出现的数据,以便删除后续的相同数据。具体的步骤如下:
1.定义一个数组count,用于记录每个数据出现的次数。
2.遍历链表,对于每个结点,将其数据的绝对值作为下标,在count数组中对应位置加1。
3.再次遍历链表,对于每个结点,查找其数据在count数组中对应的值,如果大于1,则说明该数据之前已经出现过,将该结点删除;否则继续遍历下一个结点。
代码实现如下(C++):
```c++
void deleteDuplication(ListNode *head, int n) {
int count[n] = {0};
ListNode *cur = head, *prev = nullptr;
while (cur) {
int index = abs(cur->val);
if (count[index] == 0) {
count[index] = 1;
prev = cur;
} else {
prev->next = cur->next;
delete cur;
}
cur = prev->next;
}
}
```
其中,head为单链表的头结点,n为数据的取值范围,即|n|。
需要注意的是,由于每个结点只能被访问一次,因此时间复杂度为O(m),其中m为链表的长度。
c语言链表删除重复结点仅保留一个
好的,针对您的问题,以下是一个简单的 C 语言链表删除重复结点仅保留一个的实现方法:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
void delete_duplicate(struct node* head) {
struct node *current, *runner, *duplicate;
current = head;
while (current != NULL && current->next != NULL) {
runner = current;
while (runner->next != NULL) {
if (current->data == runner->next->data) {
duplicate = runner->next;
runner->next = runner->next->next;
free(duplicate);
} else {
runner = runner->next;
}
}
current = current->next;
}
}
void print_list(struct node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = (struct node*) malloc(sizeof(struct node));
second = (struct node*) malloc(sizeof(struct node));
third = (struct node*) malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 3;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original list: ");
print_list(head);
delete_duplicate(head);
printf("List with duplicates removed: ");
print_list(head);
return 0;
}
```
在上面的代码中,我们首先定义了一个结构体 `node` 来表示链表节点,其中包含了一个整型数据 `data` 和一个指向下一个节点的指针 `next`。接着实现了一个 `delete_duplicate` 函数,它使用两个指针 `current` 和 `runner` 分别指向当前节点和当前节点之后的节点,并且在内部使用了一个 `duplicate` 指针来删除重复节点。最后,我们定义了一个 `print_list` 函数来打印链表中的所有节点。
在 `main` 函数中,我们创建了一个简单的链表,其中包含三个节点,其中第二个和第三个节点的数据相同。我们首先打印出原始的链表,然后调用 `delete_duplicate` 函数来删除重复节点,最后再次打印链表来验证删除操作是否成功。
希望这个代码可以帮助您解决问题,如果您有任何疑问,请随时问我。