您的位置:首页 > 其它

LintCode 翻转链表

2017-09-22 16:42 363 查看
翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/

public class Solution {
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if (head==null){
return head;
}
ListNode p=head;
ListNode next=head.next;
ListNode pre=new ListNode(0);
pre.next=head;

while(p!=null){
next=p.next;
p.next=pre;
pre=p;
p=next;
}
head.next=null;
return pre;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: