您的位置:首页 > 其它

反转链表

2016-04-23 12:36 337 查看
题目描述

输入一个链表,反转链表后,输出链表的所有元素。

思路:

题目中没说,当我是按没有头结点做的。从第一个元素截断链表,这两将截断后的两个链表分别称为前面的链表和后面的链表。让后面的链表采用头插入法插入前面的链表。也要注意边界条件。

package cn.yzx.nowcoder;

import cn.yzx.nowcoder.FindKthToTail.ListNode;

/**
* 题目描述
* 输入一个链表,反转链表后,输出链表的所有元素。
* @author yzx
*
*/
public class ReverseList {

public static void main(String[] args) {
ListNode head = new ListNode(-1);
ListNode testList = new ListNode(1);
ListNode testList1 = new ListNode(2);
ListNode testList2 = new ListNode(3);
ListNode testList3 = new ListNode(4);
ListNode testList4 = new ListNode(5);
head.next = testList;
testList.next = testList1;
testList1.next = testList2;
testList2.next = testList3;
testList3.next = testList4;

ListNode resNode = ReverseList.ReverseList(head);
while(resNode != null){
System.out.print(resNode.val+" ");
resNode = resNode.next;
}
}

public static class ListNode {
int val;
ListNode next = null;

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