一个已知链表 将里面正数放在原链表 负数放在新链表 使用原来的储存空间 用c语言代码表示
时间: 2024-01-04 18:41:04 浏览: 59
以下是一个简单的实现,将正数放在原链表中,负数放在新链表中:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void splitList(struct Node* head) {
struct Node *curr = head, *prev = NULL, *newHead = NULL, *newTail = NULL;
while (curr != NULL) {
if (curr->data < 0) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
if (newHead == NULL) {
newHead = newTail = curr;
} else {
newTail->next = curr;
newTail = curr;
}
curr = curr->next;
newTail->next = NULL;
} else {
prev = curr;
curr = curr->next;
}
}
if (newHead != NULL) {
newTail->next = head;
head = newHead;
}
}
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 = -2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original list: ");
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
splitList(head);
printf("\nNew list: ");
curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
return 0;
}
```
输出结果如下:
```
Original list: 1 -2 3
New list: -2
```
在这个例子中,原链表包含三个节点,数据分别为1,-2和3。`splitList`函数将负数节点放入一个新链表中,并将其从原链表中删除。在这个例子中,新链表包含一个节点,数据为-2。原链表现在只包含一个节点,数据为1和3。注意,我们使用了原来的储存空间,而没有创建任何新节点。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)