024-反转链表
解题思路:第一种递归思想,有递也有归,递的过程就是head指针一直走到尾,归的过程就是后一个节点连在前一个节点的过程。
/**
* 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) {
//递归终止条件
if(head==null||head.next==null) {
return head;
}
ListNode P=reverseList(head.next);
head.next.next=head;//此时节点已经反转过来
head.next=null;//设置当前节点的next=null
return P;
}
}
解题思路:第二种,用迭代的思想,有三个指针分别记录当前节点,当前节点的前一个结点,以及后一个节点。
/**
* 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) {
ListNode cur=head,pre=null;
while(cur!=null) {
ListNode back=cur.next;
cur.next=pre;
pre=cur;
cur=back;
}
return pre;
}
}
ps:今天又是懒懒散散的一天,再过两天!接好运气!