203 移除链表元素
思路: 使用虚拟头结点
public static ListNode RemoveElements(ListNode head, int val)
{
ListNode dummyHead = new ListNode(0, head);//使用虚拟头结点
ListNode cur = dummyHead;//不能用头结点进行遍历,否则头结点每次都会变化
while (cur.next != null)//使用while循环完成链表的遍历
{
if (cur.next.val == val)
{
cur.next = cur.next.next;
}
else
{
cur = cur.next;
}
}
return dummyHead.next;
}
//c#构建链表以及输出链表元素
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
ListNode data62 = new ListNode(6, null);
ListNode data5 = new ListNode(5, data62);
ListNode data4 = new ListNode(4, data5);
ListNode data3 = new ListNode(3, data4);
ListNode data61 = new ListNode(6, data3);
ListNode data2 = new ListNode(2, data61);
ListNode data1 = new ListNode(1, data2);
ListNode result = RemoveElements(data1, 6);
while (result != null)
{
Console.WriteLine(result.val + " ");
result = result.next;
}
Console.ReadKey();
707. 设计链表
思路: 使用虚拟头结点
关键步: 单链表如何定位到第index个元素
public class MyLinkedList {
public MyLinkedList() {
}
private int len = 0;
private ListNode dummyHead = new ListNode(0, null);
public int Get(int index) {
if(index >= len) return -1;
else{
int i = 0;
ListNode cur = dummyHead;
while(i++ <= index){ //单链表如何定位到第index个元素
cur = cur.next;
}
return cur.val;
}
}
public void AddAtHead(int val) {
ListNode tmp = new ListNode(val, dummyHead.next);
dummyHead.next = tmp;
len++;
}
public void AddAtTail(int val) {
ListNode tmp = new ListNode(val, null);
int i = 0;
ListNode cur = dummyHead;
while(i++ < len){
cur = cur.next;
}
cur.next = tmp;
len++;
}
public void AddAtIndex(int index, int val) {
if(index > len) return;
else if(index == len)
{
AddAtTail(val);
return;
}
else if(index < 0)
{
AddAtHead(val);
return;
}
else
{
int i = 0;
ListNode cur = dummyHead;
while(i++ < index){
cur = cur.next;
}
ListNode tmp = new ListNode(val, cur.next);
cur.next = tmp;
len++;
}
}
public void DeleteAtIndex(int index) {
if(index < len)
{
int i = 0;
ListNode cur = dummyHead;
while(i++ < index){
cur = cur.next;
}
cur.next = cur.next.next;
len--;
}
}
}
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
206. 反转链表
思路: 双指针法
public ListNode ReverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while(cur != null)
{
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}