LeetCode206.反转链表(C++实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28584889/article/details/84838420

问题描述:

 思路:遍历该链表,将每个节点按顺序头插法组成一条新链表。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseSiglelist(ListNode* head)
    {
        ListNode* current = head, *temp = NULL;
        head = NULL;
        while (current)
        {
            temp = current;
            current = current->next;
            temp->next = head;
            head = temp;
        }
        return head;
    }
    ListNode* reverseList(ListNode* head) {
        if(head == NULL)
            return NULL;
        return reverseSiglelist(head);
    }
};

函数reverseSiglelist可以用作一个链表反转函数,传入参数为待反转链表的头结点,返回反转后的链表头结点。

猜你喜欢

转载自blog.csdn.net/qq_28584889/article/details/84838420
今日推荐