剑指Offer-链表-(3)

知识点/数据结构:链表

题目描述:
输入一个链表,反转链表后,输出新链表的表头。

可能的测试案例:
(1)输入的链表头指针是nullptr;
(2)输入的链表只有一个节点;
(3)输入的链表有多个节点;

思路:为了正确的反转一个链表,需要调整链表中的指针的方向;需要注意为了防止链表断裂,需要定义一些节点来保存遍历到的节点的前一个节点和后一个节点。 《如下图,例子:有三个节点》
在这里插入图片描述

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode pre= null;
        ListNode next=null;
        while(head!=null){
            next=head.next;//不要考虑head.next是不是为空;是空就让next指向空。
            
            head.next=pre;
            pre=head;
            head=next;//此处是头尾相连!!!
        }
        return pre;//pre最后是一个头节点。是一个链表的头节点
        
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35649064/article/details/84798111