我是靠谱客的博主 搞怪自行车,这篇文章主要介绍206.图解双指针反转链表,现在分享给大家,希望可以做个参考。

题目要求:反转一个链表

               https://leetcode-cn.com/problems/reverse-linked-list/

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路:1. 定以结点 pre = null; cur = head; 

           2.将head 后移 (head = head.next), cur 指向 pre(cur.next = pre ;) ;然后pre,cur后移到它两的下一跳(pre  = cur;cur =head)

 

           3.若head ==null;则循环结束,链表已经反转完毕。返回pre。

           

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(head!=null){
           head = head.next;
           cur.next = pre;
           pre = cur;
           cur = head;
        }
        return pre;
     }
}

 

最后

以上就是搞怪自行车最近收集整理的关于206.图解双指针反转链表的全部内容,更多相关206内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部