19.Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

分析:题目要求是实现链表的转置。

用了三种实现:

1.递归

/*递归实现链表转置*/
	 public ListNode reverseList(ListNode head) {
		 if(head == null){
			 return null;
		 }
		 ListNode p = head;
		 if(head.next == null){
			 return head;
		 }else{	
			 ListNode list = reverseList(head.next);
			 p.next.next = p;
			 p.next = null;/*注意让这个地方最后p指向null*/
			 return list;
		}
	  }

2.迭代
l1表示已经排好倒序的头结点 ;
l2表示后面待倒排链表的头结点
l3=l2.next

 /*迭代做*/
	 public ListNode reverseList2(ListNode head) {
		 if(head == null || head.next == null){
			 return head;
		 }else{
			 ListNode l1 = head;
			 ListNode l2 = l1.next;
			 l1.next = null;/*注意链表的最后一个元素指向null*/
			 
			 while(l2.next != null){
				 ListNode l3 = l2.next;
				 l2.next = l1;
				 l1 = l2;
				 l2 =l3;
			 }			 
			 l2.next = l1;
			 return l2;			 
		 }
	    }
public ListNode ReverseList2(ListNode head) {
		 if(head == null){
			 return head;
		 }else{
			 ListNode l1 = null;
			 ListNode l2 = head;
			 
			 while(l2.next != null){
				 ListNode l3 = l2.next;
				 l2.next = l1;
				 l1 = l2;
				 l2 =l3;
			 }			 
			 l2.next = l1;
			 return l2;			 
		 }
   }



3.先遍历得到所有值,然后再重新给链表的节点赋值。
 <span style="white-space:pre">	</span>/**
	  * 先遍历得到所有值,然后再重新给链表的节点赋值 
	  */
	 public ListNode reverseList3(ListNode head) {
		 ListNode p = head;
		 ArrayList vallist = new ArrayList<Integer>();
		 while(p!=null){
			 vallist.add(p.val);
			 p = p.next;
		 }
		 p = head;
		 for(int i=vallist.size()-1;i>=0;i--){
			 p.val = (int) vallist.get(i);
			 p =p.next;
		 }
		 
		 return head;
	    }

做链表的题目要重点控制循环的结束条件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值