LCR 024
题目:LCR 024
解法一:迭代
每遍历一个节点,将该节点作为反转后的头节点,指向已返转的子链,需要注意最初遍历的节点为null
,然后才是head
节点
另外修改nextNode
的指向时,应先保留nextNode
原本的指向,用于传递给下次循环
public ListNode reverseList1(ListNode head) {ListNode temp, reverseHead = null, nextNode = head;//A -> B -> Cwhile (nextNode != null) {temp = nextNode.next;nextNode.next = reverseHead;reverseHead = nextNode;nextNode = temp;}return reverseHead;}
解法二:递归
将每个待反转的链表分为头节点和子链,反转子链后,将子链的尾节点指向原来的头节点即可。
反转后的尾节点就是原子链的头节点,可以通过head.next
获取。最后记得将原头节点指向null
public ListNode reverseList(ListNode head) {if (head == null || head.next == null) return head;//A -> B <- CListNode reverseHead = reverseList(head.next);head.next.next = head;head.next = null;return reverseHead;}