力扣链表相关题目

反转链表

题目:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

输入:head = [1,2]
输出:[2,1]
示例 3:

输入: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) {
          ListNode pre=null;
          ListNode cur=head;
          ListNode temp=null;
          while(cur!=null){
              temp=cur.next;
              cur.next=pre;
              pre=cur;
              cur=temp;
              

          }
          return pre;
    }
}
递归方法
    class Solution {
    public ListNode reverseList(ListNode head) {
        return reverse(null,head);
    }
    public ListNode reverse(ListNode pre,ListNode cur){
        if(cur==null){
            return pre;
        }
        ListNode temp=null;
        temp=cur.next;
        cur.next=pre;
        return reverse(cur,temp);
    }
}

思路:反转链表即将链表的指针指向相反的方向即可,即反转链表的指针
主要可以使用两种方法
(1)双指针的方法,即先定义一个虚拟的指针,将头节点指向虚拟的指针,将头节点的下一个节点用临时变量储存起来,再将节点依次向后移动,重复前面的步骤,最后返回临时节点即可。
(2)用递归的方法 将重复的操作定义成为一个方法

posted on 2023-02-13 11:07  小布丁儿要努力hh  阅读(61)  评论(0)    收藏  举报