LeetCode题解-206-Reverse Linked List Ⅰ

来源:互联网 发布:谷歌浏览器 for mac 编辑:程序博客网 时间:2024/04/30 05:37

原题


迭代法

解题思路

新建两个ListNode变量p1与p2存放遍历时的节点与其后驱节点,原先为P1->P2,,遍历时将其反转P2-P1,遍历结束则整个链表翻转完毕。

需要注意的是head节点在迭代之前要指向null

图解


源代码

public class Solution_iterator {    public ListNode reverseList(ListNode head) {        if(head==null||head.next==null)            return head;        ListNode p1 = head;        ListNode p2 = p1.next;        head.next = null;        while(p1!=null&& p2!=null){            ListNode t = p2.next;            p2.next = p1;            p1 = p2;            p2 = t;        }        return p1;    }}

递归法

解题思路

将head节点的后驱节点head.next递归反转,之后head.next -> head即可
其中head节点仍要单独使其指向null

图解




0 0
原创粉丝点击