定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null) return null;
ListNode pre = null;
ListNode temp = null;
while(head!=null) {
temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}