反转一个单链表
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
迭代方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//设置虚拟头结点为null值
ListNode pre = null;
//设置当前节点为头结点
ListNode cur = head;
while(cur!=null){
//链表当前节点的下一个节点
ListNode nextNode = cur.next;
//反转后的链表的当前节点的下一个节点
cur.next = pre;
//链表的虚拟头结点发生位移
pre = cur;
//链表的下一个节点位移称为当前节点
cur = nextNode;
}
//返回链表的虚拟头结点
return pre;
}
}
递归方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//递归求解的第一部分:求解最基本问题
//当head等于null或者head.next等于null的时候情况
if(head==null||head.next==null){
return head;
}
//递归求解的第二部分;把原问题转化为更小的问题
ListNode p = reverseList(head.next);
head.next.next= head;
head.next = null;
return p;
}
}
具体的测试代码请见git链接
https://github.com/minlian/node.git