15.反转链表

题目描述:

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

思路分析:

  设置两个指针,pre和next,pre指向head,next保存head.next,即pre->head->next,要想反转链表让 head指向pre, pre<-head next,然后循环更新pre和head,最后将链表反转。

代码:

/*
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;
        ListNode nowhead=null;
        if(head==null)
            return null;
        while(head!=null){   //pre->head->next   pre<-head next
            next=head.next;
            if(next==null)
                nowhead=head;
            head.next=pre;
            pre=head;
            head=next; //依次反转后面的节点
        }
         return nowhead;
    }
}
原文地址:https://www.cnblogs.com/yjxyy/p/10712519.html