Q16:反转链表
2016-07-28 23:21
302 查看
public
class Q16 {
/**
*
题目:反转链表
*
题目说明:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
*
注意:要注意空表的情况和只有一个结点的情况。
*
思路:用三个指针分别指向三个相邻的变量值。前一个结点,当前结点和后一个结点。
* 1)用当前结点now的后继指向当前结点的前驱;
* 2)将pre指向当前结点
* 3)将now指向下一个结点
*/
public
static void main(String[] args) {
ListNode head = new ListNode();
ListNode second = new ListNode();
ListNode third = new ListNode();
ListNode forth = new ListNode();
head.nextNode = second;
second.nextNode = third;
third.nextNode = forth;
head.data = 1;
second.data = 2;
third.data = 3;
forth.data = 4;
Q16 test = new Q16();
ListNode result = test.ReverseList(head);
System.out.println(result.data);
}
public
ListNodeReverseList(ListNode head){
if(head ==
null){//对链表的合法性进行判断
returnnull;
}
if(head.nextNode ==
null){//只有一个结点
return head;
}
ListNode preNode = null;//pre指向原链表的当前结点的前驱结点
ListNode nowNode = head;//now指向当前结点
ListNode reveredHead =
null;//反转链表的头结点
while(nowNode.nextNode !=
null){
ListNode next = nowNode.nextNode;//当前结点的后继结点
if(next ==
null){
reveredHead = next;//如果当前结点的后继结点的next为null,则当前结点的后继结点为反转链表后的头结点。
}
nowNode.nextNode = preNode;//1)a.nextNode=null; 2)b.nextNode=a; ...
preNode = nowNode;
//1)preNode=a; 2)preNode=b; ...
nowNode = next;
//1)nowNode=b; 2)nowNode=c; ...
}
return nowNode;//返回反转后的链表的表头
}
}
相关文章推荐
- Java中的string类详解
- 23.兄弟郊游问题
- [Android]Android 开发环境下载地址 -- 百度网盘 adt-bundle android-studio sdk adt 下载
- 微信公众平台介绍(一)
- iOS之UIViewController执行返回操作并传递参数值的两种方式
- Tyvj P1015 公路乘车
- Java中堆内存与栈内存详解
- 22.n-1位数
- hibernate配置文件如何配置?
- log4j.properties 配置详解
- 21.开灯问题
- HDU4301 Divide Chocolate(DP)
- 电梯用时
- 同步容器&并发下的容器
- 20.日期计算
- invalidate()不起作用
- OkHttp源码解析(三)——连接池复用
- 在CentOS 7上安装Docker环境
- 实例之纳税额计算
- 模板