题目 从头到尾改变指针指向:
class Solution { public ListNode reverseList(ListNode head) { ListNode pre=null; ListNode cur=head; if(cur==null||cur.next==null) return head;//头结点为空或者只有一个节点 ListNode nxt=head.next; while(cur.next!=null){ cur.next=pre; pre=cur; cur=nxt; nxt=cur.next; } cur.next=pre; return cur; } }头插法:
class Solution { public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head; ListNode dummy=new ListNode(0); dummy.next=head; ListNode pre=head; ListNode cur=head.next; while(cur!=null){ pre.next=pre.next.next; cur.next=dummy.next; dummy.next=cur; cur=pre.next; } return dummy.next; } }