如1->2->3->4->5,反转输出5->4->3->2->1
发现对地址这一块不是太熟悉。
//节点结构
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
解法1:新建空间
public ListNode rerere(ListNode head){
ListNode pre=null;
ListNode first = null;
while (head!=null){
first=new ListNode(head.val);
if(pre!=null) first.next=pre;
pre=first;
head=head.next;
}
return first;
//然后遍历输出first即可得到反转的链表
}
解法2:在原地址上操作
写了一个,乱的跟麻一样。地址都混了
假设存在链表1→2→3→∅,我们想要把它改成 ∅←1←2←3。
在遍历列表时,将当前节点的 next指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head,pre=null;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode p=reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
如 1 2 3 4 5.
递归回来的时候,p=5
head=4,那么head.next.next就是5.next=4.
然后head.next=4.next=null,组成了 5 4 null
然后再回去的时候,p=4
head=3,head.next.next=head就是4.next=3
然后head.next=3.next=null,组成了5 4 3 null.
///