题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
先上代码
public static ListNode reverseList(ListNode head) {
//申请节点,pre和 cur,pre指向null,cur指向当前节点
ListNode pre = null;
ListNode cur = head;
while (cur != null) {//当前节点不为null就一直循环
//记录当前节点的下一个节点
ListNode tmp = cur.next;
//然后将当前节点指向pre,指向反转
cur.next = pre;
//pre和cur节点都前进一位
pre = cur;//pre右移到cur位置
cur = tmp;//cur右移到tmp位置,继续循环,tmp指向cur的下一个节点
}
return pre;
}
接下来写一个测试类进行测试
package leetCode_206;
public class ReverseList {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
public static String print(ListNode listNode){//打印节点的方法
StringBuilder sb = new StringBuilder();
while (listNode!=null){
sb.append(listNode.val);
listNode = listNode.next;
}
return sb.toString();
}
}
public static ListNode reverseList(ListNode head) {
//申请节点,pre和 cur,pre指向null,cur指向当前节点
ListNode pre = null;
ListNode cur = head;
while (cur != null) {//当前节点不为null就一直循环
//记录当前节点的下一个节点
ListNode tmp = cur.next;
//然后将当前节点指向pre,指向反转
cur.next = pre;
//pre和cur节点都前进一位
pre = cur;//pre右移到cur位置
cur = tmp;//cur右移到tmp位置,继续循环,tmp指向cur的下一个节点
}
return pre;
}
public static void main(String[] args) {
ListNode listNode = new ListNode(1);//新建节点1
listNode.next = new ListNode(2);//1指向下一个节点2
listNode.next.next = new ListNode(3);//2指向下一个节点3
listNode.next.next.next = new ListNode(4);//3指向下一个节点4
System.out.println(listNode.print(listNode));//1234
listNode = reverseList(listNode);//单链表反转
System.out.println(listNode.print(listNode));//4321
}
}
解题教程欢迎访问B站https://www.bilibili.com/video/BV1pJ411s7P4?p=2
至此结束。