输入一个链表,反转链表后,输出新链表的表头。
比较简单,直接上代码
1 public ListNode ReverseList(ListNode head) { 2 if (head == null || head.next == null) 3 return head; 4 ListNode next = head.next; 5 head.next = null; 6 ListNode newHead = ReverseList(next); 7 next.next = head; 8 return newHead; 9 }
1 class Solution { 2 public ListNode reverseList(ListNode head) { 3 //申请节点,pre和 cur,pre指向null 4 ListNode pre = null; 5 ListNode cur = head; 6 ListNode tmp = null; 7 while(cur!=null) { 8 //记录当前节点的下一个节点 9 tmp = cur.next; 10 //然后将当前节点指向pre 11 cur.next = pre; 12 //pre和cur节点都前进一位 13 pre = cur; 14 cur = tmp; 15 } 16 return pre; 17 } 18 }
原文:https://www.cnblogs.com/lkylin/p/13539385.html