题目1:向有序链表中插入一个结点
思路:遍历链表,找到存放元素的正确结点位置后,插入结点
public static ListNode insertIntoSortedList(ListNode headNode, ListNode newNode) {
if (headNode == null) {
return newNode;
}
ListNode previousNode = null;
ListNode currentNode = headNode;
while ((currentNode != null) && (currentNode.getData() < newNode.getData())) {
previousNode = currentNode;
currentNode = currentNode.getNext();
}
previousNode.setNext(newNode);
newNode.setNext(currentNode);
return headNode;
}
题目2:逆置单向链表
思路1:利用栈实现
1)先获取单链表的长度,并创建相应长度的栈;
2)将单链表的数据一个一个存到栈中,然后利用栈先入后出的特性
3)从栈中取出数据生成新的单链表,即原单链表的逆置链表
思路2:使用迭代
此处使用迭代方法实现
public static ListNode reverseList(ListNode headNode) {
ListNode tempNode = null;
ListNode nextNode = null;
while (headNode != null) {
nextNode = headNode.getNext();
headNode.setNext(tempNode);
tempNode = headNode;
headNode = nextNode;
}
return tempNode;
}
题目3:如何从单链表的表尾开始输出该链表
思路1:先将链表逆置,然后遍历输出
public static void printListFromEnd2(ListNode headNode) {
if (headNode != null) {
ListNode currentNode = reverseList(headNode);
while (currentNode != null) {
System.out.print(currentNode.getData() + " ");
currentNode = currentNode.getNext();
}
System.out.println();
}
}
思路2:使用递归实现
public static void printListFromEnd1(ListNode headNode) {
if (headNode != null) {
printListFromEnd1(headNode.getNext());
System.out.print(headNode.getData() + " ");
}
}