[leetcode]Reorder List
2015-10-18 21:31
609 查看
public class Solution {
public static void reorderList(ListNode head) {
if(head==null||head.next==null)
return ;
ListNode tmp,revhead=head,pre,cur=head,next;
int len=0,lp;
while(cur!=null){
cur=cur.next;
len++;
}
lp=(len+1)/2;
cur=head;
while(lp-->1){
cur=cur.next;
}
revhead=cur.next;
cur.next=null;
cur=revhead.next;
pre=revhead;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
revhead.next=null;
//反转之后的链表头
revhead=pre;
cur=head;
while(revhead!=null){
next=cur.next;
tmp=revhead.next;
cur.next=revhead;
revhead.next=next;
cur=next;
revhead=tmp;
}
return ;
}
public static void main(String[] args) {
ListNode t1=new ListNode(1);
ListNode t2=new ListNode(2);
ListNode t3=new ListNode(3);
t1.next=t2;
t2.next=t3;
reorderList(t1);
}
}
public static void reorderList(ListNode head) {
if(head==null||head.next==null)
return ;
ListNode tmp,revhead=head,pre,cur=head,next;
int len=0,lp;
while(cur!=null){
cur=cur.next;
len++;
}
lp=(len+1)/2;
cur=head;
while(lp-->1){
cur=cur.next;
}
revhead=cur.next;
cur.next=null;
cur=revhead.next;
pre=revhead;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
revhead.next=null;
//反转之后的链表头
revhead=pre;
cur=head;
while(revhead!=null){
next=cur.next;
tmp=revhead.next;
cur.next=revhead;
revhead.next=next;
cur=next;
revhead=tmp;
}
return ;
}
public static void main(String[] args) {
ListNode t1=new ListNode(1);
ListNode t2=new ListNode(2);
ListNode t3=new ListNode(3);
t1.next=t2;
t2.next=t3;
reorderList(t1);
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统