链表问题包含:
删除节点,
插入排序,
旋转
Remove Linked List Elements
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param val, an integer
# @return a ListNode
def removeElements(self, head, val):
node=ListNode(0)#先给一个DUMMY HEAD
node.next=head
cur=node#指针
while cur and cur.next:
if cur.next.val==val:#当指针下一个为VAL
cur.next=cur.next.next#给下一个
else:
cur=cur.next#循环
return node.next#返回后面节点
Java
Insertion Sort List
30% Accepted
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
//1,dummyhead->while loop->swap
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(0);//dummyhead
while (head != null) {//head is not null
ListNode node = dummy;//node is dummy
while (node.next != null && node.next.val < head.val) {
node = node.next; //当符合要求的时候,往下走
}
//不符合要求对调swap
//node.next->head.next
ListNode temp = head.next;//head.next为TEMP
head.next = node.next;//
node.next = head;
head = temp;
}
return dummy.next;
}
}
双指针:
Remove Nth Node From End of List
两个指针,一个指针比另外一个快走N步,然后慢指针和快指针一起走。当快指针走到尽头时,正好,慢指针走到要删除的点。
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
dummy = ListNode(0);
dummy.next = head;
fast = dummy;
for i in range(0,n):
if fast == None or n==0:
return head
if fast != None:
fast = fast.next
slow = dummy
while fast.next != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next