一.题目
Reverse Linked List
Total Accepted: 9559 Total Submissions: 28250My
Submissions
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
这是一道简单的链表反转的题,并不考察什么算法,只是考察链表的基础知识。
三.实现代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* Pre = NULL; ListNode* Now = head; ListNode* Next = NULL; while(Now) { Next = Now->next; Now->next = Pre; Pre = Now; Now = Next; } return Pre; } };
四.体会
这是一道简单的题,基础题。
版权所有,欢迎转载,转载请注明出处,谢谢
时间: 2024-10-27 08:20:57