剑指Offer——题24(反转链表)

1.题目

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

2.解题思路

step1:定义三个指针:记录节点的前一个节点pre,当前节点pNode,后一个节点pNext

step2: 遍历节点,将他的next指向前一个节点pre,当pNext==null时,即此时的当前节点为反转链表后的头结点

 注意: 1.头结点为空       2.输入的链表只有一个节点

3.代码实现

public class ReverseList {

    class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode reverseList(ListNode head) {
        if(head==null){
            return null;
        }
      ListNode reverseHead=null;
      ListNode pre=null;
      ListNode pNode=head;
      ListNode pNext=head;
     while(pNext!=null){
         pNext=pNext.next;
         if(pNext==null){
             reverseHead=pNode;
         }
         pNode.next=pre;//当前节点的next指向前一个节点pre
         pre=pNode;
         pNode=pNext;
     }
    return reverseHead;
    }

    //正常功能测试
    @Test
    public void test1(){
        ListNode listNode6=new ListNode(6,null);
        ListNode listNode5=new ListNode(5,listNode6);
        ListNode listNode4=new ListNode(4,listNode5);
        ListNode listNode3=new ListNode(3,listNode4);
        ListNode listNode2=new ListNode(2,listNode3);
        ListNode listNode1=new ListNode(1,listNode2);
        ListNode reverseHead=reverseList(listNode1);
        ListNode pHead=reverseHead;
       while(pHead!=null){
           System.out.println(pHead.val);
           pHead=pHead.next;
        }
    }
    @Test
    public void test2(){

        ListNode listNode1=new ListNode(1,null);
        ListNode reverseHead=reverseList(listNode1);
        ListNode pHead=reverseHead;
        while(pHead!=null){
            System.out.println(pHead.val);
            pHead=pHead.next;
        }
    }

    @Test
    public void test3(){

        ListNode reverseHead=reverseList(null);
        ListNode pHead=reverseHead;
        while(pHead!=null){
            System.out.println(pHead.val);
            pHead=pHead.next;
        }
        System.out.println(reverseHead);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值