【剑指offer】反转链表-CSDN博客

51 阅读1分钟

思路

逐个拆解链表,将链表逐个断开并指向其前一个元素;

声明两个指针:

  • pre 用于保存拆解过程中头结点之前的节点;
  • next 用于保存用于保存拆解过程中头结点之后的节点;
public class Solution {
     public ListNode ReverseList(ListNode head) {
     
        ListNode pre=null;
        ListNode next=null;
        
        while(head!=null){
            next=head.next;     //将next指向下一个节点
            head.next=pre;    //断开头结点,指向空值pre        
            pre=head;		//将pre指向当前头
            head=next;		//将头结点指向next,即下一节点
        }
        return pre;
    }
}