使用java实现有序的单链表,并且添加一个方法,用于反转链表
1、定义链表结构
public class ListNode {
ListNode next;
Integer val;
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
}
2、反转链表
/**
* 反转链表
* @param head
*/
public static ListNode reverse(ListNode head){
ListNode reverseHead = null;
ListNode node = head;
ListNode pre = null;
while (node != null){
ListNode next = node.next;
if(next == null){
reverseHead = node;
}
node.next = pre;
pre = node;
node = next;
}
return reverseHead;
}
3、打印链表
/**
* 打印链表
* @param head
*/
public static void printList(ListNode head){
ListNode indexNode = head;
String string = "[";
while (indexNode.next != null){
string += (indexNode.val+",");
indexNode = indexNode.next;
}
string += (indexNode.val+"]");
System.out.println(string);
}
4、全部代码以及测试
public class ListNode {
ListNode next;
Integer val;
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
/**
* 反转链表
* @param head
*/
public static ListNode reverse(ListNode head){
ListNode reverseHead = null;
ListNode node = head;
ListNode pre = null;
while (node != null){
ListNode next = node.next;
if(next == null){
reverseHead = node;
}
node.next = pre;
pre = node;
node = next;
}
return reverseHead;
}
/**
* 打印链表
* @param head
*/
public static void printList(ListNode head){
ListNode indexNode = head;
String string = "[";
while (indexNode.next != null){
string += (indexNode.val+",");
indexNode = indexNode.next;
}
string += (indexNode.val+"]");
System.out.println(string);
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode();
ListNode listNode2 = new ListNode();
ListNode listNode3 = new ListNode();
ListNode listNode4 = new ListNode();
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode1.setVal(2);
listNode2.setVal(3);
listNode3.setVal(1);
listNode4.setVal(5);
ListNode.printList(listNode1);
ListNode reverseNode = ListNode.reverse(listNode1);
ListNode.printList(reverseNode);
}
}