基础数据结构
算法思路
- 明白基本的链表结构组成,可以使用头插法,对链表进行遍历的同时,改变指针方向。也可以直接改变指针方向
- 由此,代码模板如下
// 模板一
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur !=null){
ListNode next= cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
// 模板二
class Solution {
public ListNode reverseList(ListNode head) {
ListNode ans = new ListNode(0);
ListNode temp = head;
while(temp!=null){
ListNode node = temp;
temp = temp.next;
node.next = ans.next;
ans.next = node;
}
return ans.next;
}
}