剑指Offer24:反转链表

定义一个函数:输入一个链表的头结点,反转该链表并输出反转后链表的头节点。

思路:写出健壮性的代码的前提,最好写代码之前想出全面的测试用例。

1.头结点为Null      2 .只有一个节点的头结点   3.多个节点的头结点。

判断头节点是否为Null ,是return null ,若是一个头节点则return 这个节点。

定义其他的2个指针,pre和next指针置null,再while(head!=null)      {   

         先让保存下一节点next = head.next();

         反转指针       head.next() = pre;

          移动pre指针  pre = head;

          再移动head指针   head = next;

 }。

代码:

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null)
            return null;
        ListNode pre = null;
        ListNode next = null;

        while(head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

思考题:用递归来实现反转链表 

猜你喜欢

转载自blog.csdn.net/weixin_39137699/article/details/89422444