【剑指offer】十,反转链表

it2022-05-05  159

题目描述

输入一个链表,反转链表后,输出链表的所有元素。 分析:此题学过数据结构的应该会首先想到链表建立时所采用的头插法,即每一个新插入进来的点均插在链表头。代码如下: 1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 public class Solution { 11 public ListNode ReverseList(ListNode head) { 12 if(head ==null){ 13 return null ; 14 } 15 ListNode l2 = null ; 16 ListNode l2head = l2 ; 17 while(head!=null){ 18 ListNode temp = head.next ; 19 head.next = l2 ; 20 l2 = head ; 21 head = temp ; 22 } 23 24 return l2 ; 25 } 26 }

 

转载于:https://www.cnblogs.com/huntertoung/p/4765176.html


最新回复(0)