(1)实现单链表的就地逆置。
时间: 2024-05-29 15:09:04 浏览: 23
好的,这是一个算法问题。单链表就地逆置的思路是遍历链表,将每个节点接到它的前面。具体实现可以借助三个指针,分别指向当前节点、前一个节点和下一个节点。代码如下:
void reverseList(Node *head) {
if (head == nullptr || head->next == nullptr) {
return;
}
Node *prev = nullptr;
Node *curr = head;
Node *next = nullptr;
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
下一个问题,请问您有什么需要帮助的吗?
相关问题
编写一个函数,实现单链表就地逆置
好的,以下是实现单链表就地逆置的函数代码:
```c
void reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return;
}
ListNode* prev = NULL;
ListNode* curr = head;
ListNode* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
```
这个函数会将传入的单链表就地逆置,即不需要创建新的链表,只需要修改原链表中节点的指向关系即可。
java单链表就地逆置
以下是Java实现单链表就地逆置的代码:
```
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
}
```
主要思路是从头开始遍历链表,每次将当前节点的next指向前面的节点,然后将prev指向当前节点,当前节点指向下一个节点,继续遍历下去,直到遍历完整个链表。最后返回prev即为逆置后的链表头。
相关推荐
![](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)