题目描述
输入一个链表,反转链表后,输出新链表的表头。
解法1
/* 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 left=head; ListNode mid=left.next; ListNode right = mid.next; while(right!=null){ mid.next = left; left = mid; mid = right; right = right.next; } mid.next = left; head.next = null; head = mid; return head; } }
解法2
/* 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 newListNode=null; while(head!=null){ //把源链表进行头插法到新的node中 ListNode old_head = head; head = head.next; old_head.next = newListNode; newListNode = old_head; } return newListNode; } }