203 移除链表元素
题目链接:. - 力扣(LeetCode)
public static ListNode RemoveElements(ListNode head, int val)
{
var currentNode = new ListNode(0);
var headNode = currentNode;
currentNode.next = head;
while (currentNode.next!=null)
{
if (currentNode.next.val == val)
{
currentNode.next=currentNode.next.next;
}
else
{
currentNode=currentNode.next;
}
}
currentNode = headNode.next;
return currentNode;
}
707 设计链表
题目链接:. - 力扣(LeetCode)
测试用例有点难ac,看的代码随想录写的
class ListNode
{
public int val;
public ListNode next;
public ListNode(int val) { this.val = val; }
}
public class MyLinkedList
{
ListNode dummyHead;
int count;
public MyLinkedList()
{
dummyHead=new ListNode(0);
count=0;
}
public int Get(int index)
{
if (index < 0 || count <= index) return -1;
ListNode current = dummyHead;
for (int i = 0; i <= index; i++)
{
current = current.next;
}
return current.val;
}
public void AddAtHead(int val)
{
AddAtIndex(0, val);
}
public void AddAtTail(int val)
{
AddAtIndex(count, val);
}
public void AddAtIndex(int index, int val)
{
if (index > count) return;
index = Math.Max(0, index);
count++;
ListNode tmp1 = dummyHead;
for (int i = 0; i < index; i++)
{
tmp1 = tmp1.next;
}
ListNode tmp2 = new ListNode(val);
tmp2.next = tmp1.next;
tmp1.next = tmp2;
}
public void DeleteAtIndex(int index)
{
if (index >= count || index < 0) return;
var tmp1 = dummyHead;
for (int i = 0; i < index; i++)
{
tmp1 = tmp1.next;
}
tmp1.next = tmp1.next.next;
count--;
}
}
206 翻转链表
题目链接:
主要思想:保存两个节点,一个指向头,一个指向null,两个一起向后移动,需要将currentNode的下个节点 赋值为preNode的节点,同时preNode的节点要为当前current的节点实现翻转
public ListNode ReverseList(ListNode head)
{
var currentNode=head;
ListNode preNode=null;
while(currentNode!=null)
{
var temp=currentNode.next;
currentNode.next=preNode;
preNode=currentNode;
currentNode=temp;
}
return preNode;
}
递归写法,思想差不多,不过是把while拆成递归
public ListNode ReverseList(ListNode head)
{
return Reverse(head,null);
}
public ListNode Reverse(ListNode currentNode,ListNode preNode)
{
if(currentNode==null) return preNode;
var temp=currentNode.next;
currentNode.next=preNode;
preNode=currentNode;
currentNode=temp;
return Reverse(currentNode,preNode);
}