反转链表

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12633556.html

反转链表(120min)

题目链接:https://leetcode-cn.com/problems/reverse-linked-list/

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题解:
方法:使用头插法把一个链表重新组成新的链表。
思路:
1.定义一个新的链表。
2.对给的链表进行遍历。
3.每遍历一个元素,把这个元素的next指向新的链表头。
4.把新的链表头向前移动一个位置,以便下面一个元素使用头插法找到新链表头。
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode now_head=null;
        while(head!=null)
        {
           ListNode temp=head;
           head=head.next;
           temp.next=now_head;
           now_head=temp;
        }
        return now_head;
    }
}

 

posted @ 2020-04-04 19:05  萍2樱释  阅读(140)  评论(0编辑  收藏  举报