面试题24:反转链表
原创
©著作权归作者所有:来自51CTO博客作者qq59ce45caba461的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
分析:
原地逆置链表,需要操作3个链表的关系。假设i->j->k,当把j指向i的时候,就断开了j->k的指针,为了还能找到k,就需要在断开之前,将k保存下来。
解法:
package com.wsy;
class Node {
private int value;
private Node next;
public Node() {
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class Main {
public static void main(String[] args) {
Node head = init();
print(head);
head = reverse(head);
print(head);
}
public static Node init() {
Node node6 = new Node(6, null);
Node node5 = new Node(5, node6);
Node node4 = new Node(4, node5);
Node node3 = new Node(3, node4);
Node node2 = new Node(2, node3);
Node node1 = new Node(1, node2);
return node1;
}
public static void print(Node node) {
while (node != null) {
System.out.print(node.getValue() + "->");
node = node.getNext();
}
System.out.println();
}
public static Node reverse(Node node) {
if (node == null) {
return null;
}
Node prev = null;
Node current = node;
while (current != null) {
Node next = current.getNext();
current.setNext(prev);
prev = current;
current = next;
}
return prev;
}
}