Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
将链表反向是一种很重要的操作,在一些题目中经常会作为一个子步骤出现,比如143题,submission里面的最优的解法就使用了这样的一步,所以一定要熟练掌握。
题目中要求用迭代和递归两种方法实现。
首先,学习一下什么是递归和迭代(摘自http://blog.csdn.net/lg1259156776/ )https://blog.csdn.net/LG1259156776/article/details/46849809)
从直观上讲,递归是将大问题化为相同结构的小问题,从待求解的问题出发,一直分解到已经已知答案的最小问题为止,然后再逐级返回,从而得到大问题的解(一个非常形象的例子就是分类回归树 classification and regression tree,从root出发,先将root分解为另一个(root,sub-tree),就这样一直分解,直到遇到leafs后逐层返回);而迭代则是从已知值出发,通过递推式,不断更新变量新值,一直到能够解决要求的问题为止。
我的迭代算法:
我的答案:
class Solution {
public ListNode reverseList(ListNode head){
if(head==null||head.next==null) return head; //边缘条件分析
ListNode p1=head;
ListNode p2=head.next;
p1.next=null; //首先修改第一个节点的next,使它指向null。
while(p2!=null){ //开始迭代
ListNode tmp=p1;
p1=p2;
p2=p2.next;
p1.next=tmp;//修改连接关系的关键步骤
}
return p1;返回此刻的头结点。
}
}`
看了下答案 向大神膜拜,思路太清晰了:
class Solution {
public ListNode reverseList(ListNode head){
ListNode newHead=null;
while(head!=null){
ListNode next=head.next;
head.next=newHead;
newHead=head;
head=next;
}
return newHead;
}
}
这种方法的大致思路是,我先创建一个链表,链表中最初只含有一个null的尾节点,其中newhead指向该尾节点;head指向原链表的头结点,next指向原链表第二个节点,然后不断将原链表的第一个节点插到新链表的头结点位置,当对原链表最后一个节点操作完成后,创建的链表即是原链表的反向链表。
递归算法还没写,先?一下,明天再写。