题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <iostream>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    ListNode* ReverseList(ListNode* head) {
        // write code here
        ListNode* cur = head->next;
        ListNode *lastNode = head;
        ListNode *nextNode = head;
	  //判断空链表
        if(head == nullptr){
		  //空链表直接返回空指针
            return nullptr;
        }
	  
        while (cur) {
            cout << cur << "   "<< cur->val << endl;
		  //保存上一个节点位置
            nextNode = cur->next;
		  //将当前节点转向指向上一个节点,这一句达到反转的作用
            cur->next = lastNode;
		  //保存当前节点,下一个节点反转的时候需要使用到当前节点
            lastNode = cur;
		  //指向下一个节点
            cur = nextNode ;
        }
	  //因为链表当前已经是反转的状态,所以头已经是尾部了,尾部的下一个节点应当指向空
        head->next = nullptr;
	  //定义新头
        head = lastNode;
	  //返回新头
        return head;
    }
};

#链表#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务