题目描述:
给你单链表的头节点 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 -> 3ListNode 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;}
}