反转一个单链表。
运行结果
思路二:递归
class Solution { public ListNode reverseList(ListNode head) { if(head==null || head.next==null) return head; ListNode p = reverseList(head.next); head.next.next = head; head.next = null; return p; } } 运行结果 思路三:头插法代码: /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head == null || head.next == null){ return head; } ListNode new_head = null; while(head != null){ ListNode p = head; head = head.next; p.next = new_head; new_head = p; } return new_head; } } 运行结果