题目
翻转单链表
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路
第一种思路就是迭代,依次将链表中的节点放到集合中,然后通过集合的API翻转。
第二种思路使用双指针,cur指针指向head,pre初始值是null。只要cur不为空,那就一直向后遍历,将cur.next指向pre,最终cur走到链表结尾,变成null,结束。
第三种是使用递归解法。
代码
这里只介绍第二和第三种的实现。
快慢指针
public ListNode reverseList(ListNode head) {
ListNode cur=head;
ListNode pre = null;;
while(cur!=null){
//在改变链表的指向前,需要用临时变量存一下要改变的指针的指向。
ListNode temp = cur.next;
//后一个节点的next指向前一个节点
cur.next = pre;
//后一节点向前移动
pre = cur;
//前节点向前移动
cur = temp;
}
//最后一个节点就是头结点
return pre;
}
递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null||head.next==null)return head;
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
}