翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
在原地一次翻转完成
/**
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
// write your code here
ListNode *temp1,*temp2;
if(head==NULL)
return NULL;
if(head->next!=NULL){
temp1=head->next;
if(temp1->next!=NULL){
temp2=temp1->next;
temp1->next=head;
head->next=NULL;
head=temp1;
temp1=temp2;
}
else{
temp1->next=head;
head->next=NULL;
head=temp1;
return head;
}
}
else{
return head;
}
while(temp1->next!=NULL){
temp2=temp1->next;
temp1->next=head;
head=temp1;
temp1=temp2;
}
temp1->next=head;
head=temp1;
return head;
}
};
链表翻转算法
本文介绍了一种在原地一次性完成链表翻转的方法。通过调整指针的方式,实现了链表节点顺序的反转。示例中展示了一个具体的链表翻转过程,并提供了完整的C++实现代码。
1623

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



