题目描述:
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
解题思路:
采用迭代的方式: 循环将当前节点移动到前一个节点的前面,就将整个链表逆转了
/**
* 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 pre = null;
ListNode cur = head;
while(cur !=null){
//要先保存cur.next---才可以继续遍历下去
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
采用递归的方式,先取到head后面的逆转序列,再将head加上去
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//采用递归的方式
if(head==null || head.next==null)
return head;
//这里p就是倒数第二个
ListNode p = head.next;
ListNode res = reverseList(p);
head.next=null;
//将head追加上去
p.next = head;
return res;
}
}