头插法反转链表

过程分析:

  1. 原链表 1->2->3
  2. 新建new节点,指向1,1指向null,此时head更新2
  3. head(2)插入new之后,1之前,此时head更新为3
  4. head(3)插入new之后,2之前

规律总结:

通过newList保存当前节点,通过下一次操作把新的节点插入二者之间实现反转。


class Test4 {
	public static void main(String[] args) {
		ListNode head = new ListNode(1);
		head.next = new ListNode(2);
		head.next.next = new ListNode(3); // 1 -> 2 -> 3
		reverse(head);
	}

	public static ListNode reverse(ListNode head) {
		// core algorithm
		ListNode newList = new ListNode(-1);
                while (head != null) {
	            ListNode next = head.next;
	            head.next = newList.next;
	            newList.next = head;
	            head = next;

	            // print the process
	            ListNode print = newList;
	            System.out.println("");
	            while (null != print) {
	        	System.out.print(print.val + "->");
	        	print = print.next;
	            }
	        System.out.print("null");

                }
                return newList.next;
	        }

	private static class ListNode {
		ListNode next = null;
		int val;

		ListNode(int val) {
			this.val = val;
		}
	}
}

输出结果:

posted @ 2020-03-22 00:16  L7UI  阅读(676)  评论(0)    收藏  举报