反转链表
反转一个单链表。
1 2 3 4 5 6 7 8 9 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
解题思路
斩断过去,不忘前事,定义一个变量储存链表,定义另一个临时变量插入链表
解决方法
1 2 3 4 5 6 7 8 9 10 11 12 var reverseList = function (head ) { let pre = null while (head!=null ){ let tmp = head.next head.next = pre pre = head head = tmp } return pre };
反转指定位置的链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 var reverseBetween = function (head, m, n ) { const originList = new ListNode (0 ) originList.next = head let listNode = originList for (let i = 0 ; i < m - 1 ; i++) { listNode = listNode.next } let prev = null let cur = listNode.next for (let i = 0 ; i < n - m + 1 ; i++) { let next = cur.next cur.next = prev prev = cur cur = next } listNode.next .next = cur listNode.next = prev return originList.next }