链表反转头插法java_(链表)-反转链表(递归和头插法实现)

反转一个链表常用的两种实现方式:递归和头插法的方式

(1)递归实现

package dsaa.反转链表;

class Node {

int val;

Node next;

public Node(Node next, int val) {

this.val = val;

this.next = next;

}

public Node(int val) {

this.val = val;

}

}

public class Solution {

/* 采用递归来反转链表 */

public static Node reverseList(Node head) {

if (head == null || head.next == null) {

return head;

}

Node theNextOfHead = head.next;

Node newHead = reverseList(theNextOfHead);

theNextOfHead.next = head;

head.next = null;

return newHead;

}

public static void main(String[] args) {

Node head = new Node(new Node(new Node(null, 3), 2), 1);

Node cur = head;

System.out.print("原始的链表:");

while (cur != null) {

System.out.print(cur.val);

cur = cur.next;

}

Node theNodeOfCurrent = Solution.reverseList(head);

System.out.println();

System.out.print("反转过后的链表:");

while (theNodeOfCurrent != null) {

System.out.print(theNodeOfCurrent.val);

theNodeOfCurrent = theNodeOfCurrent.next;

}

}

}

(2)头插法实现

个人更青睐这一种,采用新建一个空next域的newHead头结点来指向新的反转过后的链表,另外利用了两个指针来保存当前节点和下一节点,cur表示当前节点,next表示下一节点,每次开始时都需要让next称为cur的下一节点,然后开始断开cur和next之间的联系,并每次都让newHead的next域成为当前节点的next域,第一个节点的next域就被赋成了null,后面每次都是上一节点,然后再让当前节点成为newHead的下一节点,即newHead.next = cur,并且移动当前节点的位置到下一位置。

package dsaa.反转链表;

class Node {

int val;

Node next;

public Node(Node next, int val) {

this.val = val;

this.next = next;

}

public Node(int val) {

this.val = val;

}

}

/* 采用头插法 */

public static Node reverseList(Node head) {

/**

* 头插法反转链表应该重视的是指针的变换过程

*/

/* 新建一个新链表的头指针newHead */

Node newHead = new Node(-1);

/* 用两个指针来表示当前的节点和下一节点 */

/* next指针域每次表示为当前节点的下一节点,所以一开始就别再赋值了 */

Node current = head;

Node next = null;

/* 开始判断并遍历原始的链表,构造新的链表 */

while (current != null) {

/* 先让next指针移到当前节点的下一节点中去 */

next = current.next;

/* 让现在的链表的第一个节点的下一指针域变成newHead的下一指针域 */

/* 但是newHead的一开始的下一指针域是null,所以相当于是让head变成了新链表的头结点 */

/* 但是后续的每一次就是让当前链表的头结点指向新链表的第一个节点(非newHead) */

current.next = newHead.next;

/* 再让newHead指向当前链表的头节点 */

newHead.next = current;

/* 移动当前节点到下一节点的位置 */

current = next;

}

return newHead.next;

}

public static void main(String[] args) {

Node head = new Node(new Node(new Node(null, 3), 2), 1);

Node cur = head;

System.out.print("原始的链表:");

while (cur != null) {

System.out.print(cur.val);

cur = cur.next;

}

Node theNodeOfCurrent = Solution.reverseList(head);

System.out.println();

System.out.print("反转过后的链表:");

while (theNodeOfCurrent != null) {

System.out.print(theNodeOfCurrent.val);

theNodeOfCurrent = theNodeOfCurrent.next;

}

}

}

5b6ec26bc38e5b20c1ab03928f044bd8.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值