剑指 Offer 24. 反转链表
一、题目详情
原题链接:剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <=
节点个数<= 5000
二、迭代法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode nextTemp = null; //用于暂存后继节点
ListNode pre = null;
ListNode temp = head;
while(temp != null){
nextTemp = temp.next; //暂存后继节点 temp.next
temp.next = pre; //修改next引用指向
pre = temp; //pre 暂存 temp
temp = nextTemp; //temp 访问下一节点
}
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) {
return reverse(head,null);
}
public ListNode reverse(ListNode cur,ListNode pre){
if(cur == null){
return pre; //当遍历到尾节点时返回
}
ListNode node = reverse(cur.next,cur); //递归遍历节点
cur.next = pre; //修改节点引用指向
return node; //返回反转后链表的头节点
}
}