剑指Offe6-反转链表

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

/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/
public class Solution {
   
    public ListNode ReverseList(ListNode head) {
   
        ListNode pre=null; //指向当前结点前面的那个结点
        ListNode next=null;//指向当前结点后面的那个结点
        if(head==null)
            return null;
        /* 1->2->3->4 变成 1<-2 3->4 */
        while(head!=null){
   
            next=head.next;
            head.next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务