题目:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
注意:本题与主站 206 题相同:https://leetcode-cn.com/problems/reverse-linked-list/
思路一:
将其转换为链表
再将链表倒置过来
但返回类型与条件的类型不对应,编译不通过
错误示范
class Solution {
public ListNode reverseList(ListNode head) {
List<ListNode> list= new ArrayList<ListNode>();
ListNode cur=head;
while(cur!=null){
list.add(cur);
cur=cur.next;
}
for(int i=list.size()-1;i>0;i--){
list.get(i).next=list.get(i-1);
}
list.get(0).next=null;
return list;
}
}
但是此代码在上面行不通
返回类型不对应,而且也找不到转换类型的函数
所以尝试换思路
总结:
有返回类型不同且对应不上,需进行转换思路
思路二:
使用递归的思路进行遍历
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;
}
}
思路三:
进行迭代
存储前后的位置
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}