[LeetCode 206] Reverse linked list, reverse a singly linked list.

learning target:

Goal: Use knowledge of Java data structure proficiently


Learning Content:

The content of this article: Implemented in Java: Reverse Linked List


Title description

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Problem-solving ideas

  • method one:

The first step is to define three linked list objects
. The first prevNode represents the previous node of the current node, and the initial value is null. The
second curNode represents the current node, and the initial value is the head node. The
third nextNode represents the current node. The next node

The second step is to
set the next of the current node to curNode.next=prevNode to point the next of the current node to the previous node,
and then move the three nodes backward in turn.

  • Method Two:

Traverse the original linked list, and then insert the value of the original linked list into the new linked list at a time

Implementation code

  • method one:
class Solution {
    
    
    public ListNode reverseList(ListNode head) {
    
    
     if(head==null){
    
    
     //链表为空
            return head;
        }
        if(head.next==null){
    
    
            //链表只有一个元素
            return head;
        }
    ListNode pre=null;//前一个结点
        ListNode cur=head;//当前结点
        while(cur!=null){
    
    
            ListNode latter=cur.next;//记录当前结点的下一个结点
            cur.next=pre;//将当前结点的指向逆置
            pre=cur;//结点后移
            cur=latter;//结点后移
        }
        return pre;
    }
}
  • Method Two:
 private static Node reverseList(Node head) {
    
    
       ListNode newhead=null;//新链表头结点
       ListNode cur=head;//原链表头结点
       while(cur!=null){
    
    
           ListNode tmp=new ListNode(cur.val);//记录原链表结点
           tmp.next=newhead;//将原链表结点头插到新链表
           newhead=tmp;//重置新链表头结点
           cur=cur.next;
       }
       return newhead;        
        }

Guess you like

Origin blog.csdn.net/zhangxxin/article/details/113666997