题目描述
输入一个链表,反转链表后,输出新链表的表头。
解法
解法一
(a) 为原链表
(b) 反转链表:当i把之前所有的的指针指向前一个结点,导致链表在结点 i、j 之间断裂。
所以,反转时,把 i 指向 h 时,还需一个指针记录 j 结点以防断裂。
public static ListNode reverseList(ListNode head){ if(head == null || head.next ==null){ return head; } ListNode p = head; ListNode q = null; while(p!=null){ ListNode pnext = p.next; //记录被调整的下一个元素 if(pnext == null) head = p; p.next = q; //调整指针指向 q = p; p = pnext; } return head;
}
package demo; public class Solution { public static class ListNode{ int val; ListNode next = null; ListNode(int val){ this.val = val; } } public static ListNode reverseList(ListNode head){ if(head == null || head.next ==null){ return head; } ListNode p = head; ListNode q = null; while(p!=null){ ListNode pnext = p.next; //记录被调整的下一个元素 if(pnext == null) head = p; p.next = q; //调整指针指向 q = p; p = pnext; } return head; } public static void main(String[] args) { ListNode head = null;//new ListNode(0); ListNode node1 = new ListNode(1); head = node1; ListNode node2 = new ListNode(2); node1.next = node2; ListNode node3 = new ListNode(3); node2.next = node3; ListNode node4 = new ListNode(4); node3.next = node4; ListNode node5 = new ListNode(5); node4.next = node5; ListNode node6 = new ListNode(6); node5.next = node6; ListNode node7 = new ListNode(7); node6.next = node7; ListNode node8 = new ListNode(8); node7.next = node8; ListNode node9 = new ListNode(9); node8.next = node9; ListNode node10 = new ListNode(10); node9.next = node10; ListNode cur = head; while(cur != null){ System.out.print(cur.val + " "); cur = cur.next; } ListNode reshead = reverseList(head); System.out.println(); ListNode cur2 = reshead; while(cur2 != null){ System.out.print(cur2.val + " "); cur2 = cur2.next; } } }
解法二:递归
public static ListNode reverseList(ListNode head){ if(head == null || head.next ==null){ return head; } ListNode node = reverseList(head.next); ListNode cur = node; while(cur.next != null){ cur = cur.next; //往回遍历 } cur.next = head; //指针指向前一个元素 head.next = null; //前一个元素指向后的指针设null return node; }