题目描述:输入一个链表,反转链表后,输出新链表的表头。(画图容易理解)
方法1:
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; } }
方法2:
public class Solution { public ListNode ReverseList(ListNode head) { if(head == null || head.next == null ) return head; ListNode p1 = head; ListNode p2 = head.next; ListNode p3 = p2.next; p1.next = null; while(p3!=null){ p2.next = p1; p1 = p2; p2 = p3; p3 = p3.next; } //最后一个p3=null时p2的next没有设置 p2.next = p1; return p2; } }