剑指offer_反转链表
输入一个链表,反转链表后,输出新链表的表头。
方法一、直接反转
/* 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) return null; ListNode m=null; ListNode cur=head; ListNode next=cur.next; while(next!=null){ cur.next=m; m=cur; cur=next; next=next.next; } cur.next=m; return cur; } }
方法二:使用头插法
1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 public class Solution { 11 public ListNode ReverseList(ListNode head) { 12 ListNode newList=new ListNode(-1); 13 14 while(head!=null){ 15 ListNode next=head.next; 16 head.next=newList.next; 17 newList.next=head; 18 head=next; 19 } 20 return newList.next; 21 } 22 }
方法三:
递归
1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 public class Solution { 11 public ListNode ReverseList(ListNode head) { 12 if(head==null) return null; 13 if(head.next==null) return head; 14 ListNode next=head.next; 15 head.next=null; 16 ListNode newList= ReverseList(next); 17 next.next=head; 18 return newList; 19 } 20 }

浙公网安备 33010602011771号