反轉(zhuǎn)一個單鏈表片挂。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
題解
java
代碼如下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode new_head = new ListNode(0);
ListNode ptr = head;
while(head != null) {
ptr = head.next;
head.next = new_head.next;
new_head.next = head;
head = ptr;
}
return new_head.next;
}
}