链表练习

Posted kid-xiaoyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表练习相关的知识,希望对你有一定的参考价值。

206. 反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
/**
 * 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 *new_head = NULL;
        while(head)
        {
            ListNode *next = head->next;
            head->next = new_head;
            new_head=head;
            head=next;
        }
        return new_head;
        
    }
};

以上是关于链表练习的主要内容,如果未能解决你的问题,请参考以下文章