反转单链表(Java实现)滴滴面试题
具体的图文讲解参考:链表翻转的图文讲解(递归与迭代两种实现)(百度面试)
如题:
定义一个方法(函数),实现输入一个链表的头结点,然后可以反转这个链表的方向,并输出反转之后的链表的头结点。
代码实现
解题思路:
从表头节点依次遍历,将当前节点的后继指针指向它的前驱节点即可;此时需要prev、next分表记录当前节点的前驱节点和后继节点。
Node节点类:
/**单向链表定义**/ static class Node<T> { private T value; //节点值 private Node<T> next; //后继节点 public Node() { } public Node(T value, Node<T> next) { this.value = value; this.next = next; } }
初始化n个节点的链表,代码如下:
/**初始化链表**/ private Node initLinkedList(int num) { Node head = new Node(0, null); Node cur = head; for(int i=1; i<num;i++){ cur.next = new Node(i, null); cur = cur.next; } return head; }
输出单链表方法:
/**打印链表**/ private void printLinkedList(Node head) { Node node = head; while(node != null){ System.out.println(node.value); node = node.next; } }
接下来就是关键的
/**反转链表**/ private Node reverseLinkedList(Node head) { if (head == null || head.next==null) { return head; } Node prev = null; Node next = null; while(head.next!=null){ next = head.next; //保存下一个节点 head.next = prev; //重置next prev = head; //保存当前节点 head = next; } head.next = prev; return head; }
验证结果:
Node head = initLinkedList(10); printLinkedList(head); System.out.println("**************"); //反转链表 Node node = reverseLinkedList(head); printLinkedList(node);
输出结果:
0 1 2 3 4 5 6 7 8 9 ************** 9 8 7 6 5 4 3 2 1 0
完整代码如下:
package com.bytebeats.codelab.algorithm.datastructure; /** * ${DESCRIPTION} * * @author Ricky Fung */ public class LinkedNodeDemo { public static void main(String[] args) { LinkedNodeDemo demo = new LinkedNodeDemo(); demo.test(); } public void test(){ Node head = initLinkedList(10); printLinkedList(head); System.out.println("**************"); //反转链表 Node node = reverseLinkedList(head); printLinkedList(node); } /**反转链表**/ private Node reverseLinkedList(Node head) { if (head == null || head.next==null) { return head; } Node prev = null; Node next = null; while(head.next!=null){ next = head.next; //保存下一个节点 head.next = prev; //重置next prev = head; //保存当前节点 head = next; } head.next = prev; return head; } /**初始化链表**/ private Node initLinkedList(int num) { Node head = new Node(0, null); Node cur = head; for(int i=1; i<num;i++){ cur.next = new Node(i, null); cur = cur.next; } return head; } /**打印链表**/ private void printLinkedList(Node head) { Node node = head; while(node != null){ System.out.println(node.value); node = node.next; } } /**单向链表定义**/ static class Node<T> { private T value; //节点值 private Node<T> next; //后继节点 public Node() { } public Node(T value, Node<T> next) { this.value = value; this.next = next; } } }
本文来自博客园,作者:aspirant,转载请注明原文链接:https://www.cnblogs.com/aspirant/p/16169347.html