class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
栈:
java复制代码
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
Deque<ListNode> stack = new LinkedList<ListNode>();
ListNode cur = dummy;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
for (int i = 0; i < n; ++i) {
stack.pop();
}
ListNode prev = stack.peek();
prev.next = prev.next.next;
ListNode ans = dummy.next;
return ans;
}
}
知识点:
三、两两交换链表中的结点
自己答案:
java复制代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode result=new ListNode(-1,head);
ListNode cur=result;
while((cur.next!=null)&&(cur.next.next!=null)){
//两两交换 A B C
//结点A 与 B交换
//先记录A地址 和 B后面的C的地址
ListNode temp1=cur.next;
ListNode temp2=cur.next.next.next;
//指向B
cur.next=temp1.next;
//B指向A
cur.next.next=temp1;
//A指针 = B的指针
temp1.next=temp2;
cur=cur.next.next;
}
return result.next;
}
}