206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
这里我采用的是递归的思路,要将第一个节点指向null,首先要让第二个节点指向第一个节点,而要让第二个节点指向第一个节点首先要让第三个节点指向第二个节点…最后一个节点指向前一个节点,之后返回该节点最为头结点。
最初的代码
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
head=reverse(head);
return head;
}
//在这里每个节点都要做的操作是将改节点指向前一个节点,同时将前一个节点指向null
//而终止递归的条件就是找到最后一个节点,也就是node.next。返回
public ListNode reverse(ListNode node){
ListNode headTag;
if(node.next.next!=null){
//不是最后一个节点的话就直接返回下一次递归返回的头结点
headTag=reverse(node.next);
}else{
//找到最后一个节点的话就直接返回
headTag=node.next;
}
//共同的操作
node.next.next = node;
node.next = null;
return headTag;
}
}
直接在reverseList方法中递归的优化方案
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode headTag = reverseList(head.next);
head.next.next = head;
head.next = null;
return headTag;
}
}