反转链表

反转链表

问题:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

这里有三种方法对链表进行反转:

  1. 递归
  2. 双链表(实际上只是对原链表进行变化)

递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        // 递归
        if(head==NULL||head->next==NULL) return head;
        ListNode* p=reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        return p;
    }
};

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        //栈
        if(head==NULL||head->next==NULL) return head;
        stack<ListNode*> mystack;
        while(head!=NULL)
        {
       		mystack.push(head);
            head=head->next;
        }
        ListNode* res=mystack.top();
        mystack.pop();
        ListNode* ans=res;
        while(!mystack.empty())
        {
        res->next=mystack.top();
        res=res->next;
        mystack.pop();
        }
        res->next=NULL;
        return ans;
    }
};

双链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        //双链表
        ListNode* newlist=NULL;
        while(head!=NULL)
        {
            ListNode* temp=head->next;
            head->next=newlist;
            newlist=head;
            head=temp;  
        }
        
        return newlist;
    }
};
全部评论

相关推荐

MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务