用c语言代码表示将单链表倒置,要求只利用原表的存储空间。 原单链表如下所示: 倒置后的单链表应为: 输入格式: 第一行输入n的值,表示单链表的元素个数。 第二行输入n个整数值,作为单链表的各元素值。 输出
时间: 2024-10-15 20:22:52 浏览: 65
在C语言中,可以使用迭代的方式实现单链表的倒置,不需要额外的存储空间。下面是一个示例代码,假设我们有一个结构体`ListNode`,包含`value`和`next`两个成员:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int value;
struct ListNode* next;
} ListNode;
// 创建一个新的节点
ListNode* createNode(int val) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->value = val;
newNode->next = NULL;
return newNode;
}
// 原始链表头节点
ListNode* inputList(int n) {
int val;
scanf("%d", &val);
ListNode* head = createNode(val);
for (int i = 1; i < n; i++) {
scanf("%d", &val);
ListNode* newNode = createNode(val);
newNode->next = head;
head = newNode;
}
return head;
}
// 链表倒置
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* prev = NULL;
ListNode* current = head;
ListNode* nextTemp;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
// 打印链表
void printList(ListNode* head) {
ListNode* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->value);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
int n;
scanf("%d", &n); // 输入链表长度
ListNode* head = inputList(n); // 获取原始链表
ListNode* reversedHead = reverseList(head); // 倒转链表
printf("Original List: ");
printList(head);
printf("\nReversed List: ");
printList(reversedHead);
return 0;
}
```
这个程序首先读取链表的长度和元素,创建原始链表,然后通过`reverseList`函数将其倒置,并最后打印出倒置前后的链表。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)