/// <summary>
/// 定义: 链表 一例
/// </summary>
public class ListNode
{
public int value;
public ListNode next;
public ListNode(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
public ListNode getNext()
{
return next;
}
public void setNext(ListNode next)
{
this.next = next;
}
//========================
//打印链表 head头指针
public static void printList(ListNode head)
{
ListNode current = head;
while (current != null)
{
Console.Write(current.getValue() + "、");
current = current.getNext();
}
Console.WriteLine("");
}
//删除节点
public static void deleteNode(ListNode head, ListNode toBeDeleted)
{
if (toBeDeleted == null || head == null) return;
if (toBeDeleted.next != null)
{ //删除的是中间节点
ListNode temp = toBeDeleted.next;
toBeDeleted.value = temp.value;
toBeDeleted.next = temp.next;
}
// 【注意】这部分代码不起作用,故注释了。
// else if (head == toBeDeleted) {
// // 如果头结点就是要删除的节点
// head = null;
// }
else
{
ListNode temp = head;
while (temp.next != toBeDeleted)
{
temp = temp.next;
}
temp.next = null;
}
}
//查找倒数第k个节点
public static ListNode findKthToTail(ListNode head, int k)
{
if (head == null || k <= 0)
{
return null;
}
ListNode prePoint = head;
ListNode postPost = head;
while (k-- > 0)
{
prePoint = prePoint.next;
if (prePoint == null)
{
return null;
}
}
while (prePoint != null)
{
prePoint = prePoint.next;
postPost = postPost.next;
}
return postPost;
}
//反转链表
public static ListNode reverseList(ListNode head)
{
ListNode reverseHead = null;
ListNode post = head;
ListNode pre = null;
while (post != null)
{
pre = post.next;
post.next = reverseHead;
reverseHead = post;
post = pre;
}
return reverseHead;
}
//合并两个排序的链表
public static ListNode mergeList(ListNode h1, ListNode h2)
{
ListNode pHead = new ListNode(-1), p = pHead;
while (h1 != null && h2 != null)
{
if (h1.value < h2.value)
{
p.next = h1;
h1 = h1.next;
}
else
{
p.next = h2;
h2 = h2.next;
}
p = p.next;
}
if (h1 == null) p.next = h2;
if (h2 == null) p.next = h1;
return pHead.next;
}
//两个链表的第一个公共结点
public static ListNode getFirstIntesection(ListNode l1, ListNode l2)
{
ListNode p1 = l1, p2 = l2;
int len1 = 0, len2 = 0;
while (p1 != null)
{
p1 = p1.next;
len1++;
}
while (p2 != null)
{
p2 = p2.next;
len2++;
}
ListNode pLong = l1, pShort = l2;
int gap = len1 - len2;
if (len1 < len2)
{
pLong = l2;
pShort = l1;
gap = len2 - len1;
}
while (gap-- > 0)
{
pLong = pLong.next;
}
while (pShort != null)
{
if (pLong == pShort) return pShort;
pShort = pShort.next;
pLong = pLong.next;
}
return null;
}
//========================
}
链表 一例
最新推荐文章于 2024-08-13 14:59:01 发布