Java-206. 反转链表【力扣】

反转一个单链表。

示例:

输入: 9->5->2->7->3->NULL
输出: 3->7->2->5->9->NULL

在这里插入图片描述
代码要求:

/** 
* Definition for singly-linked list. 
* * public class ListNode {
* *     int val;
* *     ListNode next; 
* *     ListNode(int x) { val = x; } 
* * }
* */

代码实现:

public class LinkedListTest{
    
    
 static class ListNode{
    
    
  int val;
  ListNode next;
  public ListNode(int val) {
    
    
   this.val=val;
  }
 }
 public ListNode reverseList(ListNode head) {
    
    
  if(head==null) {
    
    
   //空链表不需要逆置
   return null;
  }
  if(head.next==null) {
    
    
   //如果链表中只有一个元素也不需要逆置
   return head;
  }
  ListNode newHead=null;
  ListNode cur=head;
  ListNode prev=null;
  while(cur!=null) {
    
    
   ListNode next=cur.next;
   if(next==null) {
    
    
    //当前的cur就是原来链表的末尾
    newHead=cur;
   }
  //逆置的核心操作:更新三兄弟的指向位置
  cur.next=prev;
  prev=cur;
  cur=next;
  }
 return newHead;
 }
}

猜你喜欢

转载自blog.csdn.net/weixin_44378053/article/details/105278238