开发者社区> 问答> 正文

输入一个链表,反转链表后,如何输出新链表的表头呢?

已解决

输入一个链表,反转链表后,如何输出新链表的表头呢?

展开
收起
游客ihzapojsw2ysk 2022-04-03 09:20:27 860 0
1 条回答
写回答
取消 提交回答
  • 推荐回答

    head无数据版本:

        public ListNode ReverseList(ListNode head) {
           
    		if(head.next == null || head.next.next == null) {
    			return head;
    		}
    		//辅助指针,遍历原来的链表
    		ListNode cur = head.next.next;
    		ListNode next = null; //指向cur的下一个节点 防止断链
    		ListNode reverseHead = null;
    		while( cur != null) {
    			next = cur.next;//暂时保存后面有用
    			cur.next = reverseHead.next;//cur的下一个节点指向新链表的最前端
    			reverseHead.next = cur;//cur连接到新的链表最顶端
    			cur = next;
    		}
    		
            return reverseHead;
    	}
    }
    
    

    head有数据版本:

        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;
        }
    }
    
    
    
    2022-04-03 10:53:13
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载