1. JZ6 从尾到头打印链表
输入:
{1,2,3}
返回值:
[3,2,1]
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//用来存储链表中节点的值。
Stack<Integer> reverse = new Stack<>();
while(listNode != null){
reverse.push(listNode.val);
listNode = listNode.next;
}
//创建的题目要求的数据类型来存储反向的节点值。
ArrayList<Integer> result = new ArrayList<>();
while(!reverse.isEmpty()){
//将值从栈中弹出,并添加到ArrayList中
result.add(reverse.pop());
}
return result;
}
2. 反转链表
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode node = ReverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
3. 合并两个有序链表
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null) return list2;
if(list2==null) return list1;
if(list1.val<list2.val){
list1.next = Merge(list1.next,list2);
return list1;
} else {
list2.next = Merge(list1,list2.next);
return list2;
}
}
4 两个链表第一个公共节点
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode l1 = pHead1, l2 = pHead2;
while(l1 != l2){
l1 = (l1==null)?pHead2:l1.next;
l2 = (l2==null)?pHead1:l2.next;
}
return l1;
}
5. 删除链表的某个节点
public ListNode deleteNode (ListNode head, int val) {
while(head != null && head.val == val){
head = head.next;
}
ListNode prev = head;
if(prev!=null){
while(prev.next!=null){
if(prev.next.val == val){
prev.next = prev.next.next;
}else{
prev = prev.next;
}
}
}
return head;
}
6 删除链表重复节点
public ListNode deleteDuplication(ListNode head) {
if(head == null || head.next == null){
return head;
}
//两个循环,用来应付“1-1-2-2-3-3-4-5…”格式的连续重复结点
while(head != null && head.next != null && head.val == head.next.val){
while(head != null && head.next != null && head.val == head.next.val){
head = head.next;
}
head = head.next;
}
if(head!=null ){
head.next = deleteDuplication(head.next);
}
return head;
}
评论