反转单向链表
单向链表的节点只有一个指针指向下一个元素。
struct ListNode{
int val;
ListNode* next;
};
ListNode* reverseList(ListNode* head){
ListNode* newhead=nullptr;
while(head){
ListNode* next=head->next;
head->next=newhead;
newhead=head;
head=next;
}
return newhead;
}
另一种方法,先将head的位置就绪,再将new的位置就绪
ListNode* reverseList(ListNode* head){
ListNode* newhead=nullptr;
while(head){
ListNode* temp=head;
head=head->next;
temp->next=newhead;
newhead=temp;
}
return newhead;
}
反转双向链表
struct DoubleNode{
int val;
DoubleNode* prev;
DoubleNode* next;
};
DoubleNode* reverseList(DoubleNode* head){
DoubleNode* pre=nullptr;
DoubleNode* next=nullptr;
while(head){
next=head->next;
head->next=pre;
head->prev=next;
pre=head;
head=next;
}
return pre;
}

这篇博客介绍了如何反转单向链表和双向链表。提供了两种不同的方法来实现单向链表的反转,通过改变节点的next指针来完成。对于双向链表的反转,同时修改了节点的next和prev指针,使得链表顺序反转。这些算法对于理解链表操作和数据结构的反转具有实践价值。
206

被折叠的 条评论
为什么被折叠?



