leetcode.206 反转链表

题目描述:反转链表

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

思路:

设立三个指针,pre,cur,next
pre指向当前节点的上一个节点
cur指向当前节点
next指向当前节点的下一个节点
遍历链表,每次把当前节点cur指向上一个节点pre,然后三个指针都往后移动一位
终止条件,当前节点cur==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) {
        // 思路
        // 设立三个指针,pre,cur,next
        // pre指向当前节点的上一个节点
        // cur指向当前节点
        // next指向当前节点的下一个节点
        // 遍历链表,每次把当前节点cur指向上一个节点pre,然后三个指针都往后移动一位
        // 终止条件,当前节点cur==null了
        // 返回 pre
        if(head == null)
            return head;
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = cur;
        while(cur!=null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

 

posted @ 2019-12-30 09:29  smallone1  阅读(115)  评论(0)    收藏  举报