# 必会算法：反转链表Ⅰ

##题目

``````package com.dai.common;

public class Node {
public Integer value;
public Node next;

public Node() {
}

public Node(Integer value) {
this.value = value;
}

public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}

@Override
public String toString() {
Node temp = this;
StringBuilder str = new StringBuilder();
while (temp != null) {
str.append(temp.value).append("->");
temp = temp.next;
}
str.append("null");
return str.toString();
}
}
``````

##解题思路

##算法图解

cur指向第二个节点

** 注意观察 ！**

pre指向的链表就是反转后的链表啦！

##代码实现

``````package com.dai.code;

import com.dai.common.Node;

// 当链表为空，或者长度为1的时候走这里
}
// 当链表只有两个节点的时候
Node next = cur;
pre.next = null;

// 当链表有三个及以上节点的时候
while (next != null) {
next = next.next;
cur.next = pre;
pre = cur;
cur = next;
}

return pre;
}
}
``````

``````public class ReverseLinkedList1 {
public static void main(String[] args) {
for (int i = 2; i < 10; i++) {
temp.next = new Node(i);
temp = temp.next;
}
}
}
``````

—end—

THE END