206.双指针反转链表

徘徊边缘 提交于 2019-12-21 01:27:03

题目要求:反转一个链表

               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;则循环结束,链表已经反转完毕。

代码:

/**
 * 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;
     }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!