Reverse Linked List

Reverse Linked List,第1张

概述Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULLOutput: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?  

Reverse a singly linked List.

Example:

input: 1->2->3->4->5->NulLOutput: 5->4->3->2->1->NulL

Follow up:

A linked List can be reversed either iteratively or recursively. Could you implement both?

 

 

/** * 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 *pre = new ListNode(0),*cur = head;        pre -> next = head;        while (cur && cur -> next) {            ListNode* temp = pre -> next;            pre -> next = cur -> next;            cur -> next = cur -> next -> next;            pre -> next -> next = temp;        }        return pre -> next;    }};

总结

以上是内存溢出为你收集整理的Reverse Linked List全部内容,希望文章能够帮你解决Reverse Linked List所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1024256.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存