題目:
分析:很簡單的一個反轉列表,這裏用一趟掃描完成翻轉,也可以用棧保存沒個結點信息再拼起來,但比較耗時。
反轉即是將next的指向翻轉,並且首結點=原來的末尾結點即可
用一個結點記錄下一個結點->把當前結點的next反轉->將當前結點賦給新鏈表的next->當前結點重新指向下一個結點
代碼:
/**
* 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 newHead = new ListNode(-1);
while (head != null) {
//先取下一結點
ListNode next = head.next;
//head.next執行新鏈表的首結點,注意:新鏈表的首結點是newHead.next
head.next = newHead.next;
//newHead.next指向head,完成反轉
newHead.next = head;
//head重新指向next,接着遍歷
head = next;
}
return newHead.next;
}
}