输入一个链表,反转链表后,输出新链表的表头。

//方案一:测试

public class Solution {code

public ListNode ReverseList(ListNode head) {

       ListNode cur=head;
       ListNode temp=null;
       ListNode pre=null;
       
       while(cur!=null){
           temp=cur.next;
           cur.next=pre;
           pre=cur;
           cur=temp;
       }
    
    return pre;
}

}开发

//方案二:io

public class Solution {class

public ListNode ReverseList(ListNode head) {

      
       ListNode temp=null;
       ListNode pre=null;
       
       while(head!=null){
           temp=head.next;
            head.next=pre;
           pre=head;
           head=temp;
       }
    
    return pre;
}

}变量

推荐用方案一:方案二是我为了测试实现逆序须要最少的临时变量为2个,而方案二改变别人给入的值,通常开发不推荐这么作List

相关文章
相关标签/搜索