赞
踩
题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
题目如下:
解一:反转链表
/** * 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=NULL,*cur=head; while(cur!=NULL){ ListNode* temp=cur->next; cur->next=pre; pre=cur;cur=temp; } return pre; } };
解二:递归
思路:
/** * 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) { if(head==NULL||head->next==NULL) return head; ListNode* newHead=reverseList(head->next); head->next->next=head; head->next=NULL;//方便下次反转 return newHead;//永远是返回后的头节点 } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。