首页 > 其他 > 详细

Jan 10 - Reverse Linked List;Data Structure; Linked List; Pointer; Iteration & Recursion

时间:2016-01-11 14:03:47      阅读:219      评论:0      收藏:0      [点我收藏+]

Iteration:

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode tail = head.next;
ListNode cur = head;
while(tail!= null){
ListNode nex = tail.next;
tail.next = head;
cur.next = nex;
head = tail;
tail = nex;
}
return head;
}
}

 

Recursion:

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode cur = reverseList(head.next);
head.next.next = head;
head.next = null;
return cur;

}

}

Jan 10 - Reverse Linked List;Data Structure; Linked List; Pointer; Iteration & Recursion

原文:http://www.cnblogs.com/5683yue/p/5120897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!