定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* 实现思路
* 定义root,current指针,然后并将head置为头结点
* root:作为头插法的临时指针
* current:移动指针(遍历链表)
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
// 头插法
// 定义root,current指针
ListNode root = head;
ListNode current = head;
// 将head置为头结点
head = new ListNode(-1);
head.next = null;
// 遍历链表
while(current!=null){
// 提前移动current,防止断链
current = current.next;
// 拼接链表
root.next = head.next;
head.next = root;
root = current;
}
return head.next;
}
}