反转一个单链表。

    示例:
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    作者:力扣 (LeetCode)
    链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnnhm6/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. //借鉴org
    11. public ListNode reverseList1(ListNode head) {
    12. if(head == null||head.next==null){
    13. return head;
    14. }
    15. ListNode p = reverseList(head.next);
    16. head.next.next =head;
    17. head.next=null;
    18. return p;
    19. }
    20. //org
    21. public ListNode reverseList(ListNode head) {
    22. if(head == null){
    23. return null;
    24. }
    25. ListNode pre=null;
    26. ListNode cur=head;
    27. ListNode next=cur.next;
    28. // pre.next=null;
    29. // cur.next=pre;
    30. while(cur !=null){//&& next !=null
    31. // pre.next=pre;
    32. next=cur.next;
    33. cur.next=pre;
    34. pre =cur;
    35. cur =next;
    36. //next=next.next;
    37. }
    38. return pre;
    39. }
    40. }