题目描述:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:
head = [1,2,3,4,5]
输出:
[5,4,3,2,1]
代码实现:
1.根据题意创建一个结点类:
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
2.反转链表具体实现:
public class Main{
public static void main(String[] args) {
//创建一个简单的链表: 1 -> 2 -> 3
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
//反转操作
ListNode res = reverseList(head);
//查看结果
ListNode now = res;
while (now != null) {
if (now.next != null) {
System.out.print(now.val + "->");
} else {
System.out.print(now.val);
}
now = now.next;
}//3->2->1
}
public static ListNode reverseList(ListNode head) {
//前驱指针
ListNode pre = null;
//当前指针
ListNode current = head;
//后继指针
ListNode next;
//反转操作
while (current != null) {
//保存后继结点信息
next = current.next;
//当前结点指向前驱
current.next = pre;
//pre指向当前结点
pre = current;
//当前结点指针指向下一个结点
current = next;
}
//pre为反转之后的头结点
return pre;
}
}