[LeetCode]206. Reverse Linked List(链表反转)

Reverse a singly linked list.

click to show more hints.

Subscribe to see which companies asked this question.

利用循环。

 public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) return head;
ListNode pre = head;
head = head.next;
pre.next = null;
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}

递归版


 public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) return head;
ListNode pre = head;
head = head.next;
ListNode newhead = reverseList(head);
pre.next = null;
head.next = pre;
return newhead; }
}

 
上一篇:mybatis与mysql中的Date和String之间转换


下一篇:CString 与 std::string 相互转化