1.題目描述
2.思路
使用迭代法
(1)定義一個前指針
(2)然后定義兩個變量 curr(head),curr.next。
(3)curr和curr.next交換位置(只要當前指針不為空,執行兩兩交換)
3.代碼實現
/*** Definition for singly-linked list.* 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; }* }*/
class Solution {public ListNode reverseList(ListNode head) {//假設鏈表為 1→2→3→?,我們想要把它改成 ?←1←2←3ListNode prev=null;ListNode curr=head;while(curr!=null){//定義一個next指針,存儲臨時變量ListNode next=curr.next;curr.next = prev;prev = curr;curr = next;}return prev;}
}