Singly-linked list/Element removal: Difference between revisions
Content added Content deleted
(Category:VBA examples needing attention) |
(→{{header|C sharp}}: Added C# (unsafe translation of C)) |
||
Line 197: | Line 197: | ||
1 3 |
1 3 |
||
</pre> |
</pre> |
||
=={{header|C sharp}}== |
|||
===Tasteful & unsafe=== |
|||
{{trans|Taste|version=273489}} |
|||
Semantically identical translation of Torvalds' tasteful C version using C# unsafe pointers: |
|||
<lang csharp>using System; |
|||
using System.Runtime.InteropServices; |
|||
static unsafe class Program |
|||
{ |
|||
ref struct LinkedListNode |
|||
{ |
|||
public int Value; |
|||
public LinkedListNode* Next; |
|||
public override string ToString() => this.Value + (this.Next == null ? string.Empty : " -> " + this.Next->ToString()); |
|||
} |
|||
static void Remove(LinkedListNode** head, LinkedListNode* entry) |
|||
{ |
|||
// The "indirect" pointer points to the |
|||
// *address* of the thing we'll update |
|||
LinkedListNode** indirect = head; |
|||
// Walk the list, looking for the thing that |
|||
// points to the entry we want to remove |
|||
while (*indirect != entry) |
|||
indirect = &(*indirect)->Next; |
|||
// .. and just remove it |
|||
*indirect = entry->Next; |
|||
} |
|||
static void Main() |
|||
{ |
|||
// Allocate like real C! |
|||
var head = (LinkedListNode*)Marshal.AllocHGlobal(sizeof(LinkedListNode)); |
|||
head->Value = 1; |
|||
head->Next = (LinkedListNode*)Marshal.AllocHGlobal(sizeof(LinkedListNode)); |
|||
head->Next->Value = 2; |
|||
head->Next->Next = null; |
|||
LinkedListNode copy = *head; |
|||
Console.WriteLine("original: " + head->ToString()); |
|||
Remove(&head, head); |
|||
Console.WriteLine("after removing head: " + head->ToString()); |
|||
head = © |
|||
Console.WriteLine("restored from copy: " + head->ToString()); |
|||
Remove(&head, head->Next); |
|||
Console.WriteLine("after removing second node: " + head->ToString()); |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre>original: 1 -> 2 |
|||
after removing head: 2 |
|||
restored from copy: 1 -> 2 |
|||
after removing second node: 1</pre> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |