一:解题思路
链表是递归定义的,所以关于链表的大部分问题也可以用递归来解决。当然也可以不用递归来解决这个问题。这里来介绍2种方法,一种是递归方法,一种是非递归的方法。
二:完整代码示例 (C++版和Java版)
递归版C++
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* ret = NULL; if (head == NULL) { ret = NULL; } else if (head->next == NULL) { ret = head; } else { ListNode* guard = head->next; ret = reverseList(head->next); guard->next = head; head->next = NULL; } return ret; } };
递归版Java
class Solution { public ListNode reverseList(ListNode head) { ListNode ret=null; if(head==null) { ret=null; } else if(head.next==null) { ret=head; } else { ListNode guard=head.next; ret=reverseList(head.next); guard.next=head; head.next=null; } return ret; } }
迭代法C++:
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* cur = head; ListNode* pre = NULL; while (cur != NULL) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } };
迭代法Java:
class Solution { public ListNode reverseList(ListNode head) { ListNode cur=head; ListNode pre=null; while(cur!=null) { ListNode next=cur.next; cur.next=pre; pre=cur; cur=next; } return pre; } }
原文地址:https://www.cnblogs.com/repinkply/p/12445049.html
时间: 2024-11-07 11:32:04