Total Accepted: 73458
Total Submissions: 198280
Difficulty: Easy
Reverse a singly linked list.
如题,将一个链表进行翻转。例如初始的是[1-2-3-4-5-6]
转换后为[6-5-4-3-2-1],看了题目后,毫无逻辑和想法。然后看到提示说,可以用递归或是遍历,然而还是不行。
受之前的递归的思想影响,我认为可以做,但是这其中的逻辑理不顺,还是不熟练,于是参考其他人的答案
1 recursion。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null) return null;
if(head.next==null) return head;
ListNode p = head.next;
ListNode n = reverseList(p);
head.next = null;
p.next = head;
return n;
}
}
2. iteration
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
// 1 <-2 3
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head;//前后顺序的不一致也会报错
ListNode pre = head;
ListNode p = head.next;
pre.next = null;
ListNode nxt;
while(p!=null) {
nxt = p.next;
p.next = pre;
pre = p;
p = nxt;
}
return pre;
}
}
第二种方法理解起来简单些,第一种还是要看看,不太理解。第二种可以说是一种笨方法,但是我就是没想到……
大牛之路~~~~~~~~~~~~~~~任重而道远~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~·~~
忧伤……………………