标签:solution link class com rev reverse 逆置 反转 struct
题目链接:反转链表
方法一:递归解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return myReverseList(head);
}
ListNode* myReverseList(ListNode* head){
if(head == NULL || head->next == NULL){
return head;
}
ListNode* newHead = myReverseList(head->next); //先反转后面的链表
head->next->next = head;
head->next= NULL;
return newHead;
}
};
方法二:借助于辅助指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* last = NULL;
ListNode* p,*q;
p = head;
while(p){
q = p->next;
p->next = last;
last = p;
if(q == NULL){
head = p;
}
p = q;
}
return head;
}
};
标签:solution link class com rev reverse 逆置 反转 struct
原文地址:https://www.cnblogs.com/ManOK/p/13723525.html