1. 题目
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
2. 代码
/**
* @author LanceQ
* @version 1.0
* @time 2021/4/24 20:26
*/
public class ReverseList {
public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
ListNode e = new ListNode(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
System.out.println(a);
System.out.println(reverseList(a));
}
private static ListNode reverseList(ListNode head) {
ListNode next=null;
ListNode pre=null;
ListNode curr=head;
while (curr!=null){
//保存下一个节点
next=curr.next;
//当前节点指向上一个节点(第一次的时候指向空)
curr.next=pre;
//移动到上一个节点(第一次的话,就是从null节点移动到head头结点)
pre=curr;
//现在要操作的位置,就是移动到下一个节点(第一个的话,就是从头结点移动到头结点的下一个节点)
curr=next;
}
return pre;
}
}
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
运行结果:
ListNode{val=1, next=ListNode{val=2, next=ListNode{val=3,
next=ListNode{val=4, next=ListNode{val=5, next=null}}}}}
ListNode{val=5, next=ListNode{val=4, next=ListNode{val=3,
next=ListNode{val=2, next=ListNode{val=1, next=null}}}}}